jQuery - help needed on ID selector when id is an

2020-07-25 09:13发布

问题:

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!

回答1:

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\\]")


回答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.