5

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.

RetroCoder
  • 2,444
  • 10
  • 51
  • 80

3 Answers3

11

You were close...

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

jsFiddle Demo

kapa
  • 75,446
  • 20
  • 155
  • 173
Mark K
  • 571
  • 1
  • 3
  • 13
5

you can use start with selector:

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

or:

$("input[name^='Top']:checkbox")
Ram
  • 140,563
  • 16
  • 160
  • 190
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();
Community
  • 1
  • 1
Christofer Eliasson
  • 31,342
  • 6
  • 71
  • 100
  • 2
    From the manual: `The bare $(':checkbox') is equivalent to $('*:checkbox'), so $('input:checkbox') should be used instead.` – kapa Jul 05 '12 at 18:04
  • And I upvoted. Also, `:checkbox` is deprecated so it might be better to use `[type="checkbox"]`. – kapa Jul 05 '12 at 18:08