I am new to javascript and I am trying to change the state of check boxes by checking for their id in get query string values. For example, if we have the following url http://localhost/aasd/index.php?category[]=74
, I want to change the checkbox with id 74 to be checked.
I am trying to do it with the code below but it's not working
$(document).ready(function() {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
document.getElementById(pair[1]).checked = true;
}
pair[1] produces undefined74 I cant change check box state with that. I need to pass 74 to document.getElementById(pair[1]).checked = true;
for the check box to be checked.
Any help would be appreciated
try this.. did it with an assumptions that url will have only one parameter.
$(document).ready(function() {
var url = window.location.href;
document.getElementById(url.substr(url.indexOf('=') + 1)).checked = true;
});
Check out this code:
$(document).ready(function() {
qsArray = new Array();
var query = "http://localhost/aasd/index.php?category[]=74";
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
$("#"+pair[1]).attr("checked",true); // this will make the checkbox checked when it encounters check box with id 74 I have created a check box with id 74 in my jsfiddle
}
});
Link to fiddle: https://jsfiddle.net/d5wbo91m/2/