Eric Eric - 5 months ago 9
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];
});


Where
"lock369"
and
"lock935"
are set to constants just for my sanity to ensure the page is loading properly. The problem is no matter how I setup
"lock935"
it comes out as checked even when
wl[2]
is zero. (I have text boxes
"test1"
-
"test3"
displaying the 3 elements of
wl
so I am sure they are getting the correct values from the database they're pulled from, via
data.php
).

Originally I had all three checkboxes set to their respective elements of
wl
and the same issue occurs for all of them so it's not something funny with only
"lock935"
. I have also tried assigning the values of
wl
to individual variables and setting
document.getElementById("lockXXX").checked
equal to those variables, this didn't solve the issue. I also tried putting
wl[X]
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 :)

Thanks!

Answer

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.

Examples:

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

OR

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.

Comments