9

I'm trying to find a selector in jQuery that select all inputs that are checkboxes and their name contains a specific word like "top" or "Top". Having trouble b/c its selecting other checkboxes.

Is it possible to use something like:

$("input[name*='top'] type:checkbox").each etc?

Top 1<input type="checkbox" name="Top1" /><br />
Top 2<input type="checkbox" name="Top2" /><br />
Top 3<input type="checkbox" name="Top3" /><br />
Top 4<input type="checkbox" name="Top4" /><br />

Bottom 1<input type="checkbox" name="Bottom1" /><br />
Bottom 2<input type="checkbox" name="Bottom1" /><br />
Bottom 3<input type="checkbox" name="Bottom1" /><br />
Bottom 4<input type="checkbox" name="Bottom1" /><br />

I only want to select the check boxes which contian the word "top" in its name.

3 Answers 3

14

You were close...

$("input[type='checkbox'][name^='Top']").each()

jsFiddle Demo

Sign up to request clarification or add additional context in comments.

5 Comments

I think these selectors are case sensitive, aren't they?
So I just add two of the box selectors? And ^='Top' translates to Top or top?
@MarkK just another note, for case insensitive you can use .filter()
@RetroCoder It is case-sensitive. If you write ^='Top', it will match Top but not top.
@bažmegakapa demo always helps thanks NOTE: *='Top' is case-sensitive as well (I didn't know that)
7

you can use start with selector:

$("input[name^='Top']")

or:

$("input[name^='Top']:checkbox")

1 Comment

Please note that :checkbox is deprecated.
5

I believe you could combine the :checkbox selector and the attribute-contains selector:

$("input:checkbox[name*='top']").each(); 

Not sure if it needs to be case insensitive, in that case you could have a look at this SO question.

Update:

As bažmegakapa points out in his comment, :checkbox selector is deprecated according to the documentation. Therefor it is probably better to use:

$("input[type=checkbox][name*='top']").each();

2 Comments

From the manual: The bare $(':checkbox') is equivalent to $('*:checkbox'), so $('input:checkbox') should be used instead.
And I upvoted. Also, :checkbox is deprecated so it might be better to use [type="checkbox"].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.