0

I have the following checkboxes:

<div class="row">
    <div class="large-2 columns"><input  id="contactTypesCheckbox[12]" name="contactTypesCheckbox[12]" class="contactTypesCheckbox" type="checkbox" value="Billing" />&nbsp;Billing</div>
    <div class="large-2 columns"><input  id="contactTypesCheckbox[15]" name="contactTypesCheckbox[15]" class="contactTypesCheckbox" type="checkbox" value="Creative" />&nbsp;Creative</div>
... etc ...
</div>

Onload, I do some ajax and I pull down json that includes an array of items indicating which checkboxes should be checked.

        $.each(data.contactTypes, function(key, contactType) {
            // key is = 15 in my test
            $('#contactTypesCheckbox[key]').prop('checked', true);
        });

I would therefore expect contactTypesCheckbox[15] to be checked, but it isn't, with no error.

What am I doing wrong?

Thank you so much

2
  • Don't have [] in the IDs. It is only useful in name Commented May 30, 2013 at 19:58
  • @mplungjan.... it's useful when selecting by id... Commented May 30, 2013 at 19:59

1 Answer 1

4

Variables are not expanded inside strings in Javascript, you need to concatenate:

$('#contactTypesCheckbox\\['+key+'\\]').prop('checked', true);

You also need to escape the brackets because otherwise they have special meaning in selector syntax.

See also this question:

What are valid values for the id attribute in HTML?

regarding using special characters like [] in ID strings. It's allowed in HTML5, but not HTML4. And because of the above need to escape, it would be best not to use it.

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

3 Comments

Actually, isnt it just not working since [] mean something in CSS/Jquery? Like $('#id[name]') will select an object #id with the attribute name?
@Karl-AndréGagnon Good catch, I fixed to escape the brackets (yes, I think this works).
Thanks, that worked, I should have thought about the expansion issue, but I wouldn't have caught the escapes

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.