I want to select an option from the select tag in html containing 2 options and based on the option I have selected a related checkbox gets checked how can I achieve this? Here is my code:
Html:
Javascript:
function Select()
{
var Option=document.getElementById("select").value;
if(Option="Lahore"){
document.getElementById("chkbox-lahore").checked = true;
}
else{
document.getElementById("chkbox-karachi").checked = true;
}
}
PS. How can I do this with jQuery? Thanks
Sachin SinghPosted May 18, 2022, 12:16 PM
Shazma BatoolPosted May 19, 2022, 4:53 AM
Shazma BatoolPosted May 18, 2022, 2:13 PM
Fixed, my bad.. guys enclose your jQuery code in document.ready(func...
Note: This is when you have your js code in a sepearate .js file
i.e.
$(document).ready(function(){
$("#select").change(function(){
var selected=$(this).val();
$('[id^="chkbox-"]').prop('checked', false);
$("#chkbox-"+selected).prop('checked', true);
});
});
Within a single file of .html just enclose this code inside and don't forget to add cdn of latest jQuery you can find at https://releases.jquery.com/ in
tag of your html document( i.e. .html file)Sachin SinghPosted May 18, 2022, 1:11 PM
Shazma BatoolPosted May 18, 2022, 1:08 PM
Shazma BatoolPosted May 18, 2022, 12:22 PM
Thank you very much! @Sachin Singh it worked1
Shazma BatoolPosted May 18, 2022, 11:58 AM
@Sachin Singh thanks here last is the paragraph element with a bootstrap class "lead" on it , okay what I want to do is to select a city from the select tag and what happens is that after the selection of city related checkbox gets checked.
Here see I have selected the Lahore option and Karachi checkbox gets checked which is wrong this is the issue still persisting tried both JavaScript and jQuery
Again the code:
Select Tag:
CheckBox:
JavaScript:
function Select()
{
var Option=document.getElementById("select").value;
if(Option="Lahore"){
document.getElementById("chkbox-lahore").checked = true;
}
else{
document.getElementById("chkbox-karachi").checked = true;
}
}
jQuery:
$("#select").change(function(){
var selected=$(this).val();
$(".chkbox"+selected).prop('checked', true);
});
Sachin SinghPosted May 18, 2022, 10:09 AM