1

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

The problem remains, this is a console log of the checkbox [prevObject: n.fn.init[1], context: document, selector: ":checkbox[value="Trieste"]"]context: documentlength: 0prevObject: n.fn.init[1]selector: ":checkbox[value="one"]"proto: n[0]
Is that the case? Can you run the code in the snippet?
yes but at this point i think there could be a problem somewhere else. I'll look now to find the problem :D Thanks anyways!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.