Cristian Bregant
Cristian Bregant

Reputation: 1906

Multiple checkbox set checked html

I have an array in js that contains some name of checkbox i want to set checked. The problem is i cannot do it properly and i dont know why i'm wrong This is my code

var array = ['one','two word','three'];
for(var i = 0; i < array.length;i++)
$(':checkbox[value="'+array[i]+'"]').prop('checked', true);

With this HTML

<input type="checkbox" name="one[]" value="two word">
<input type="checkbox" name="one[]" value="four">
<input type="checkbox" name="one[]" value="one">

With this code my checkbox remain uncheked, can someone tell me why?

Upvotes: 1

Views: 4348

Answers (2)

Richard Hamilton
Richard Hamilton

Reputation: 26434

True is not a valid property value for the checked attribute. The value can either be omitted or has to be checked

var array = ['one','two word','three'];

for(var i = 0; i < array.length;i++) {
    $(':checkbox[value="'+array[i]+'"]').prop('checked', 'checked');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="one[]" value="two word">
<input type="checkbox" name="one[]" value="four">
<input type="checkbox" name="one[]" value="one">

Here's the specification from the W3C

https://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#h-17.4

Upvotes: 3

NinjaCodeMonkey007
NinjaCodeMonkey007

Reputation: 31

It worked for me except for one item that had Three for a value instead of FOUR..

I modified your code and got all three to check You can set a value http://www.w3schools.com/jsref/prop_checkbox_value.asp

<input type="checkbox" name="one[]" value="two word">
<input type="checkbox" name="one[]" value="four">
<input type="checkbox" name="one[]" value="one">

var array = ['one','two word','four'];
for(var i = 0; i < array.length;i++) {
$(':checkbox[value="'+array[i]+'"]').prop('checked', true);
}

here is a fiddle Sample fiddle

Upvotes: 0

Related Questions