hyphen
hyphen

Reputation: 3440

jquery .prop() on checkbox not working

Currently beating my head against a wall wondering why I can't seem to set the checked property of a checkbox based on the the value of a variable.

I'm trying to make a page editable. When the user chooses to edit the page, the current values get stored in sessionStorage and recalled in order to replace any changed values with their original value if the user cancels. I've stored the original checked values (true or false) in session storage and I'm trying to use those values to populate the checked state on cancel (this occurs in an each loop triggered by a button click). The below code is simplified to only include what I feel is the "problem" bits.

var value = sessionStorage.getItem(key);
console.log(key + ' = ' + value); //produces the correct key/value pair
$('input[name="' + key +'"]').prop('checked') === value; 

the checkboxes always revert to whatever the current value is.

Here's what I've also tried:

$('input[name="' + key +'"]').prop('checked', value);
$('input[name="' + key +'"]').prop(':checked', value);
$('input[name="' + key +'"]').attr('checked', value);

and pretty much every other combination I can possibly think of. Any help would be greatly appreciated.

NOTE:

I can sub out the variable to a simple true/false static value and it functions correctly. So if I do the below, it will set all the checkboxes false or true depending on what I enter:

$('input[name="' + key +'"]').prop('checked', false);

Upvotes: 0

Views: 3062

Answers (1)

JJJ
JJJ

Reputation: 3332

For boolean attributes like checked, you have to use Boolean values. Since you were using a string, the value was always going to be true.

$(element).prop ("checked", false) //false
$(element).prop ("checked","false") //true

Upvotes: 2

Related Questions