views:

51

answers:

4

I'm trying to select the id's of dynamic input fields in my code. When clicking a button, the form will create a form field like this:

<td><input type="text" id="field_a_1"></td>
<td><input type="text" id="field_b_1"></td>
<td><input type="text" id="field_c_1"></td>

When I click on the button again I get this:

<td><input type="text" id="field_a_2"></td>
<td><input type="text" id="field_b_2"></td>
<td><input type="text" id="field_c_2"></td>

What I want to do is select only the field id that I need to pull the value from that particular input and pass it to a variable like this:

var example = $(":input:eq(0)").val();

I know that by adding the :eq(0) after the :input selector it will only grab the id for field_a_1, so how do I set it up so that I can pull just the field that I need to assign it to a variable?

+1  A: 

That is what the ID is for. So you can single out a particular element.

$('#field_b_2').val();   // Will return the element with that ID.

The # indicates that you are looking for an element with an ID, as opposed to . which would look for an element (or elements) with a class:

$('.someClass').val();   // Will return elements with that class

Please remember that IDs may not be shared among elements. Only one element may have a particular ID.

Classes, on the other hand, can be shared among as many elements as you need.

patrick dw
Yes, this is what I was looking for. Thanks!
rshivers
+1 - This is probably what he's looking for with the class, but I can't really tell from the question.
Nick Craver
A: 

If you want only the id of the element you should do:

var example = $(":input:eq(0)").attr("id");

And then you can access the field again later with:

$("#" + example).show();    //or whatever you want to do
Malfist
You can just do `var example = $(":input").attr("id");` :)
Nick Craver
but he needs to select a specific one with an index. If he needs anything but the first one, your code wouldn't work.
Malfist
@Malfist - Since you're not passing a variable into `:eq(0)` that's beside the point :) But yes, what I posted is just a quicker shortcut for your *specific* posted code.
Nick Craver
A: 

I'm not quite sure if I understand what you want correctly, but it sounds like

$('input[id$=_2]').each(function(){
   alert($(this).val());
});
jAndy
A: 

your Input Ids keep changing like : When you click first time it will All: field_a_1 then , field_a_2, etc.

you simply using this to getting the correct values.

$('input[id^=field_]').each(function(){
   alert($(this).val());
});
ricky roy