2

I have an input element defined as follows:

<input type="checkbox" name="custom_15[1]" id="custom_15[1]" value="1" />

When I tried with $("#custom_15[1]") selector, it didn't work. Whereas, document.getElementById("custom_15[1]") did work.

What am I doing wrong here?

Thank you!

Andy E
  • 338,112
  • 86
  • 474
  • 445
anupam
  • 756
  • 5
  • 11

2 Answers2

11

First off, an id attribute should not contain square brackets. It's just not valid. It can contain letters, numbers, underscores, hyphens, colons and dots.

In the answer to this question there's a hint that jquery even has problems with dots and colons:

What are valid values for the id attribute in HTML?

So try to switch to valid ids. If you can't, use proper escaping:

$("#custom_15\\[1\\]")
Community
  • 1
  • 1
neurolabs
  • 542
  • 3
  • 8
  • 1
    +1. @anupam: the main point of this answer is that you should avoid invalid ID attributes. They may not be treated equally by all browsers and you may experience interoperability issues. – Andy E Nov 23 '10 at 14:03
2

True, you can't have square brackets.

Do you have to have the same name for the "name" and "id" fields?

Worse has to come you can always add a unique class to your input and find it in JS through that. ie

<input type="checkbox" name="custom_15[1]" class="test" id="custom_15[1]" value="1" />

And then in your JS use this

$(".test")

Hope this helps.

denislexic
  • 10,786
  • 23
  • 84
  • 128