11

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?

4
  • No, they are NOT duplicate IDs. If you look more carefully, you'll see that one group starts with cc and the other starts with gc.
    – EmmyS
    Mar 20, 2013 at 17:23
  • 1
    for future reference. .live has been deprecated api.jquery.com/live you should be using .on instead api.jquery.com/on Mar 20, 2013 at 17:24
  • @iAmClownShoe - I'm aware, but due to the CMS we're working with, we're stuck with an older version of jQuery.
    – EmmyS
    Mar 20, 2013 at 17:25
  • fair enough. like i said, for future reference :-) Mar 20, 2013 at 17:25

2 Answers 2

16

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

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

0
4

Filter your selector using the "ends with" selector.

http://api.jquery.com/attribute-ends-with-selector/

$('[id^="cc-"]').filter('[id$="idx"');

And make sure to include quotes.

2
  • is .filter() faster than $('[id^=cc-][id$=1]')?
    – mpapec
    Jun 24, 2013 at 14:38
  • @mpapec Possibly, but that would be a micro-optimization. Use whatever method best fits the needs of your application.
    – Brad M
    Jun 24, 2013 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.