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!
4 Answers 4
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
2 Comments
new Array I must ask, how exactly do you expect that to work? For starters you're calling for elements with the class name check, which none of your elements have, then you're just having a statement without any assignment or anything... You're also creating an array that just gets thrown away because split creates a new array. Further, instead of your string splitting, just something like var temp = [1,3,5]; would work fine... And finally you use for...in on an array, which is bad because arrays have properties beside their keys (such as length and several methods)...
Anyway, what you need is something more like:
(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 Comment
Try this:
$(document).ready(function(){
$("input[type='checkbox']").each(function(){
if( $(this).index() % 2 == 0 ){
$(this).attr('checked','checked');
}
});
});
You can play around with the fiddle here - http://jsfiddle.net/EuXQF/
Comments
$(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');
}
});
}
}