Lurk21
Lurk21

Reputation: 2337

Having trouble checking a variable checkbox with jQuery

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

Upvotes: 0

Views: 373

Answers (1)

Barmar
Barmar

Reputation: 782165

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.

Upvotes: 4

Related Questions