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

Lurk21
  • 2,307
  • 12
  • 37
  • 55

1 Answers1

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.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    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 May 30 '13 at 19:56
  • @Karl-AndréGagnon Good catch, I fixed to escape the brackets (yes, I think this works). – Barmar May 30 '13 at 20:00
  • Thanks, that worked, I should have thought about the expansion issue, but I wouldn't have caught the escapes – Lurk21 May 30 '13 at 20:03