jayant rawat jayant rawat - 1 year ago 82
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')};
localStorage.setItem("payment", JSON.stringify(favs));

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

if (!payment.length) {return};

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download