Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector help - how to find element whose ID starts and ends with specific characters

I have a page that's created dynamically. It can have a number of different radio buttons with ID's like so:

<input type="radio" id="cc-radio-opt-0" />
<input type="radio" id="cc-radio-opt-1" />
<input type="radio" id="gc-radio-opt-0" />
<input type="radio" id="gc-radio-opt-1" />

In order to write change functions, I'm doing something like this:

$('[id^=cc-radio-opt-]').live("change", function() {
    var idx = $(this).attr('id').split('-').pop(); 
});

This works well. But now, inside that change function, I need to hide a bunch of other related fields. They are named like this:

<input type="text" id="cc-number-0" />
<input type="text" id="cc-month-0" />
<input type="text" id="gc-number-0" />
<input type="text" id="gc-month-0" />
<input type="text" id="cc-number-1" />
<input type="text" id="cc-month-1" />
<input type="text" id="gc-number-1" />
<input type="text" id="gc-month-1" />

I need to be able to grab all the fields whose IDs begin with "cc" and end with the same number as the radio button that's been clicked (determined by the idx variable. I know I can get all the fields that start with "cc" by doing this:

$('[id^=cc-]');

But how can I also indicate that they need to end with whatever idx is? In other words, if the cc-radio-opt-1 radio is clicked, how can I get only cc-number-1 and cc-month-1?

like image 407
EmmyS Avatar asked Mar 20 '13 17:03

EmmyS


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 element by id in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

Which is the correct form of using ID selector in jQuery?

For id selectors, jQuery uses the JavaScript function document. getElementById() , which is extremely efficient. When another selector is attached to the id selector, such as h2#pageTitle , jQuery performs an additional check before identifying the element as a match.

Which selects elements that have the specified attribute with a value beginning exactly with a given string?

attributeStartsWith selector Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.


1 Answers

Well, you were almost there... $('[id^=cc-][id$=1]')

DEMO:http://jsfiddle.net/pavloschris/nr3ad/

like image 138
xpy Avatar answered Nov 15 '22 21:11

xpy