jayant rawat jayant rawat - 1 month ago 7
Javascript Question

Checked the checkbox if localStorage returns value true

I am trying to save multiple select values in local storage and the data is setting and getting successfully in and from local storage but the box is not checked by the jquery.

Here is the

of my code and below is the jquery code I am using :

$('.cmn').on('click', function() {
var fav, favs = [];
$('.cmn').each(function() { // run through each of the checkboxes
fav = {class: $(this).attr('class'), value: $(this).prop('checked')};
//console.debug(fav);
favs.push(fav);
});
localStorage.setItem("payment", JSON.stringify(favs));
});

$(document).ready(function() {
var payment = JSON.parse(localStorage.getItem('payment'));

if (!payment.length) {return};
//console.debug(payment);

for (var i=0; i<payment.length; i++) {
console.debug(payment[i]);
//alert("."+payment[i].class);
$("."+payment[i].class).prop('checked', payment[i].value);
}
});

Answer

Working fiddle.

You should add the index i in :eq() to specify the index of the element since all the elements have the same class cmn :

$("."+payment[i].class+':eq('+i+')').prop('checked', payment[i].value);

Hope this helps.