Selecting the correct input field using jquery
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 ho开发者_如何转开发w do I set it up so that I can pull just the field that I need to assign it to a variable?
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.
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
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());
});
精彩评论