views:

28

answers:

1

How can I check check-boxes (on page load) according to value of check-boxes using jQuery? I have list of values that I have stored within localstorage (Long live HTML5 !!) A sample data would be

something_random|something_random2|something_random3

And basically I want to read each value and make sure onload checkboxes that already have those values are checked.

I have already written;

my_cookie=localStorage.getItem('chosen_ones');

      $.each(my_cookie.split("|"), function(index, values) {
               if((values==val)&&(values!=null)&&(values!="")&&(values!="null")&&(values!="")){
                 $('input[value='+values+'').attr('checked', true);
            }
        });

However this didn't work...How can I fix it?

+2  A: 

I would suggest something along the lines of:

$('input[type=checkbox][value='+values+']').attr('checked', true);

Notice the type, and the closing ']'.

Victor Nicollet
sorry I edited my post a little late. can you help me with this new situation?
JohnRoach
of course. I edited my post as well.
Victor Nicollet
I'm using $(':checkbox:not(:checked)').each(function(){ val= $(this).val(); $.each(my_cookie.split("|"), function(index, values) { if((values==val) } });});However this time it just freezes why that may be?
JohnRoach
The query already selects all the checkboxes with the appropriate values by itself, so the $(':checkbox:not(:checked)').each is not useful here. The $.each(my_cookie...) loop should be enough.
Victor Nicollet
yes but my "val" is the value of the check box I only want to check the check box if both values mach (i.e. the value from the local storage and the value of the checkbox match)
JohnRoach
This is what the [value='+values+']' does: select only the checkboxes that match the value.
Victor Nicollet