How can I check the box if I have an array of values?

I have the following 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 am using the following code, but it does not 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!

+4
source share
4 answers

Description

You can loop through the array with for(i=0;i!=temp.length;i++) and use the attribute selector to get the correct flag.

See my jsFiddle example and demo

Example

 $(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"); } }); 

Additional Information

+7
source

I have to ask, how exactly do you expect this to work? To start, you call elements with the name of the check class that none of your elements have, then you just have an instruction without any task or something else ... You also create an array that just throws because split creates new array. Also, instead of your line splitting, just something like var temp = [1,3,5]; will work fine ... And finally you use for...in in the array, which is bad because arrays have properties next to their keys (e.g. length and several methods) ...

In any case, you need something more:

 (function() { var elms = document.querySelectorAll('input[type=checkbox]'), l = qsa.length, i; for( i=0; i<l; i++) { elms[i].checked = (elms[i].value % 2 == 1); } })(); 
+1
source

Try the following:

 $(document).ready(function(){ $("input[type='checkbox']").each(function(){ if( $(this).index() % 2 == 0 ){ $(this).attr('checked','checked'); } }); }); 

You can play the violin here - http://jsfiddle.net/EuXQF/

+1
source
 $(document).ready(function(){ var array = "1,3,5,2"; check_value(array); }); function check_value(val){ var array = val.split(","); for (i=0;i<array.length;i++){ //alert(array[i]); $("input[type='checkbox']").each(function(){ if( $(this).val() == array[i]){ $(this).attr('checked','checked'); } }); } } 
-one
source

Source: https://habr.com/ru/post/1392472/


All Articles