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 SinghRank #66 · 26.2K reputationPosted May 18, 2022, 8:16 AM EDT
Sachin SinghRank #66 · 26.2K reputationPosted May 18, 2022, 9:11 AM EDT
Sachin SinghRank #66 · 26.2K reputationPosted May 18, 2022, 6:09 AM EDT
Shazma Batool91 reputationPosted May 18, 2022, 7:58 AM EDT
@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);
});
Shazma Batool91 reputationPosted May 18, 2022, 8:22 AM EDT
Thank you very much! @Sachin Singh it worked1
Shazma Batool91 reputationPosted May 18, 2022, 10:13 AM EDT
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)Shazma Batool91 reputationPosted May 18, 2022, 9:08 AM EDT
Shazma Batool91 reputationPosted May 19, 2022, 12:53 AM EDT