Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I checked checkbox, if I have an array of values?

I have the folowing inptuts!

<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />

After using jQuery I want my result to look like this:

<input type="checkbox" value="1" checked />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" checked  />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" checked />

I use following code, but it doesn't work.

$(document).ready(function() { 
    var str = '1,3,5';
    var temp = new Array();
    temp = str.split(",");
    for (a in temp ) {
        //$('.check').valueOf().checked;
        $('.check').val(append(temp[a])).checked;
        //$('#c').append();
    }
});

Thanks in advance!

like image 728
dido Avatar asked Feb 21 '23 18:02

dido


1 Answers

Description

You can loop through your array using for(i=0;i!=temp.length;i++) and use the attribute selector to get the right checkbox.

Check out my sample and this jsFiddle Demonstration

Sample

$(document).ready(function() { 
    var str = '1,3,5';
    var temp = new Array();
    temp = str.split(",");
    for (i=0; i!=temp.length;i++) {
        var checkbox = $("input[type='checkbox'][value='"+temp[i]+"']");
        checkbox.attr("checked","checked");
    }
});

More Information

  • jsFiddle Demonstration
  • jQuery - Selectors
  • jQuery - .attr()
like image 106
dknaack Avatar answered Mar 02 '23 23:03

dknaack