Eric Eric - 1 year ago 64
Javascript Question

javascript assign variable value to checkbox status in html page

I am very new to javascript, and this seems like a very simple problem but despite many similar posts none seem to point to a solution for me.

I have the following code in a script of an html page:

$.get( "data.php", { getlocks: 1}, function( data ) { //Pull checkbox status from database (so it isn't lost on a page refresh)
wl = data.split(" ");
document.getElementById("lock369").checked = 1;
document.getElementById("lock399").checked = 0;
document.getElementById("lock935").checked = wl[2];
document.getElementById("test1").value = wl[0];
document.getElementById("test2").value = wl[1];
document.getElementById("test3").value = wl[2];

are set to constants just for my sanity to ensure the page is loading properly. The problem is no matter how I setup
it comes out as checked even when
is zero. (I have text boxes
displaying the 3 elements of
so I am sure they are getting the correct values from the database they're pulled from, via

Originally I had all three checkboxes set to their respective elements of
and the same issue occurs for all of them so it's not something funny with only
. I have also tried assigning the values of
to individual variables and setting
equal to those variables, this didn't solve the issue. I also tried putting
in paranthesis, quotes, single quotes, etc. and nothing made a difference.

As I mentioned I'm very new to js so if this is a simple negligence on my part just kindly yell at me for it and I'll correct my ways in the future :)


Answer Source

There is nothing wrong with using 0 and 1 as boolean, just make sure that if it is coming from your database in string form that you call parseInt on it or cast it to a Number.


document.getElementById("lock935").checked = parseInt(wl[2], 10);


document.getElementById("lock935").checked = Number(wl[2]);

parseInt will return NaN in the case of an empty string and using Number() will return 0. Both NaN and 0 will result in an unchecked box so it's really up to you.

Edit: fixed some verbiage in explanation and a typo in the code.