jQuery - help needed on ID selector when id is an

2020-07-25 08:48发布

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!

2条回答
We Are One
2楼-- · 2020-07-25 09:31

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\\]")
查看更多
虎瘦雄心在
3楼-- · 2020-07-25 09:49

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.

查看更多
登录 后发表回答