Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery selector to get all select dropdowns with ID pattern

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.

like image 973
Ray S. Avatar asked Sep 30 '13 13:09

Ray S.


People also ask

What selector would I use to query for all elements with an ID that ends with a particular string?

To get the elements with an ID that ends with a given string, use attribute selector with $ character.

How do you select all elements with an ID?

The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

How can use multiple ID selectors in jQuery?

Approach: Select the ID's of different element and then use each() method to apply the CSS property on all selected ID's element. Then use css() method to set the background color to pink to all selected elements. Display the text which indicates the multiple ID selectors.

Which selector selects all elements in jQuery?

:input Selector Selects all input, textarea, select and button elements.


2 Answers

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

like image 166
Anton Avatar answered Oct 07 '22 01:10

Anton


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

$('select[id^=begin_]').each(function(){...})
like image 36
Arun P Johny Avatar answered Oct 06 '22 23:10

Arun P Johny