cjl750 cjl750 - 1 year ago 117
jQuery Question

How to get attribute value with jQuery and extract substring from a result

I have a list of text inputs whose values I want to manipulate based on the values of some select inputs. The two sets of inputs have IDs with parallel constructions, such as:

<select id="foo-dog-bar>, <input type="text" id="foo-dog-baz>
<select id="foo-cat-bar>, <input type="text" id="foo-cat-baz>
<select id="foo-fish-bar>, <input type="text" id="foo-fish-baz>
<select id="foo-bird-bar>, <input type="text" id="foo-bird-baz>

In order to be able to find the matching text input, I need to search for the select input with corresponding ID. In the above example, that's the ID with the same animal name in the middle of it.

Here is what I have so far, with my question being what to do about the

jQuery('select[id$="-points"]').change(function() {

var value = jQuery(this).val(),
arr = ['cat', 'dog', 'fish', 'bird'],
criteria = jQuery(this)..., // whichever string in arr its ID contains
bar = jQuery(this).parent().find('#foo-'+criteria+'-bar').val();

// do stuff...


How can I search the ID of
for a string contained in the
array and make that string the
variable? The only thing I can find when searching for this type of thing is retrieving the index of the array items, but that doesn't help me here. I want the actual string.

Thanks in advance.

Answer Source
  1. To select an id attribute value of html tag

    criteria = jQuery(this).attr('id'); // just call an .attr('id');
  2. To select element by ID with jQuery - just as with pure JS(javascript), you do not need to find element within nested elements as ID is a unique element per DOM/PAGE

  3. You can use split function to get values from the string:

    criteria = criteria.split('foo-')[1].split('-baz')[0];

Full example:

   jQuery('select[id$="-points"]').change(function() {
         var value = jQuery(this).val(),
         arr = ['cat', 'dog', 'fish', 'bird'];
         criteria = jQuery(this).attr('id'); 
         criteria = criteria.split('foo-')[1].split('-baz')[0]; // get the value you want using split() function
         bar = jQuery('#foo-'+criteria+'-bar').val();
         // do other stuff...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download