Indika Rajapaksha
Indika Rajapaksha

Reputation: 1168

Selecting select boxes with a text pattern and a number in jQuery

I need to select the list of select boxes with the id pattern as follows.

id_social_media-0
id_social_media-1
id_social_media-2

I can not use $('select[id^=id_social_media-').each() since there is a hidden element as id_social_media-__empty. I tried with id_social_media-\d, but it does not work.

Upvotes: 0

Views: 48

Answers (2)

Thallius
Thallius

Reputation: 2619

Why not simple do an oldschool for loop?

for(let index = 0; index < numberOfItems; index++)
{
   let Element = $('select[id^=id_social_media-'+index);
   ...

If you don’t know the number, use a while loop and stop on no result in element:

var index = 0,
    elements = Array(),
    Element = $('select[id^=id_social_media-'+index);
while (Element.length) {
    elements[index++] = Element;
    Element = $('select[id^=id_social_media-'+index);
}

Upvotes: 0

PHP Guru
PHP Guru

Reputation: 1566

You could use the :not selector to exclude results you don't want:

$("select[id^=id_social_media-]:not([id=id_social_media-__empty])")

Upvotes: 1

Related Questions