In our previous article which was JQuery :: How to copy contents of a div into another div? we discussed how we can copy contents of one div into another. Today we will discuss how we can access elements which have the same id.
Suppose you have the following HTML page:
<input type=’text’ name=’exampleText’ id=’exampleText’ />
<input type=’text’ name=’exampleText’ id=’exampleText’ />
As you can see that the id of both input elements in the above code is “exampleText”, this is normally needed when elements are generated dynamically either via JQuery or via an ajax call.
You can access multiple elements with same id using the following JQuery call:
$(document).ready(function()
{
$(“[id=exampleText]“).each(function(index, element)
{
// do your thing here…
}
}
Now to get values from the elements you can do the following:
$(document).ready(function()
{
$(“[id=exampleText]“).each(function(index, element)
{
var textValue = $(this).val();
}
}
In the above Java Script we are telling JQuery that there are multiple elements with the same id that is why we use the .each function and then we are storing the value of the current element in textValue variable.
You are not free to use the textValue whatever way you want. You can add it in a javascript array and send it to an ajax call or you can use the single value and change the values in other fields as you wish.
We will keep updating our Jquery Tips section every 4 days, please subscribe to our feed and also share our articles on Facebook and Google Plus so other’s can benefit from our insight. Please feel free to send us your comments below, on how we can improve.