9

What is the simplest way to iterate through all select drop downs with ID's matching a pattern using jquery. for example:

<select id="begin_1_end">...</select>

<select id="begin_32_end">...</select>

<select id="begin_42_end">...</select>

<select id="dontgetme_2_end">...</select>

<select id="begin_12_dontgetme">...</select>

to iterate through the first 3 selects only.

Ray S.
  • 1,192
  • 3
  • 15
  • 27
  • Similar to: http://stackoverflow.com/questions/1487792/jquery-find-element-whose-id-has-a-particular-pattern/1487882 – cdmckay Sep 08 '15 at 02:17

3 Answers3

32

Try this with attribute-starts-with-selector/

$('select[id^="begin"]').each(function () {
    console.log(this.id);
});

or you could use attribute-ends-with-selector

$('select[id$="end"]').each(function () {
    console.log(this.id);
});

Update

To select the first 3 you can use :lt(3) like this

$('select[id^="begin"]:lt(3)').each(function () {
    console.log(this.id);
});

DEMO

Update

To combine the selectors you can do this

$('select[id^="begin"][id$="end"]').each(function () {
    console.log(this.id);
});

DEMO

If you want to select an element with id that starts with begin OR end you can do this using , to get two different selectors

$('select[id^="begin"],select[id$="end"]').each(function () {
    //                ^
    console.log(this.id);
});

DEMO

Anton
  • 32,245
  • 5
  • 44
  • 54
  • thanks. how do you combine both the beginning and end patterns? please see the updated question. thnx. sometimes the beginning pattern matches but not the ending one. – Ray S. Sep 30 '13 at 14:12
  • In your updated question you want to select only the first three, then one of the recent updates in my answer should work. Have you tested? @RayS. – Anton Sep 30 '13 at 14:14
3

use attribute starts with selector, then use .each() to iterate through them

$('select[id^=begin_]').each(function(){...})
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Try using attribute starts with selector

  $("select[id^='begin_'").each(function(){
  //your stuff
  })
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120