1

I have a dynamic web page where the content may contain between 1 and 10 links, provided in text boxes, similar to the following:

<input size="50" id="link" value="http://Something.Something" type="text">
<input size="50" id="link" value="http://SomethingElse.Something" type="text">

I need javascript to be able to read all of the links, and be able to manipulate the data (store in array, output to screen, etc)

I know that I can read a single id using the following

var link = document.getElementById('link');

Which will return the first match - but, how can I do a loop or obtain all the values for all the links, bearing in mind that the number of links cannot be determined beforehand?

P.S. I have tried using getElementsByTagName('input') but there are more inputs on the page, which means it's getting more results than I'd like it to get.

KeyszerS
  • 684
  • 9
  • 29
  • 1
    Id must be unigue. You cant have multiple items with the same Id – laaposto Feb 03 '14 at 10:19
  • if its possible for you add a common class to all the inputs where you will file links and then fetch all elements with that class name as http://stackoverflow.com/questions/1933602/how-to-getelementbyclass-instead-of-getelementbyid-with-javascript – Harshada Chavan Feb 03 '14 at 10:22

4 Answers4

5

You can make them all have names and search by name.

<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>

Then you can get it with:

var vrows = document.getElementsByName("vrow");
alert(vrows.length);
TheOneWhoPrograms
  • 629
  • 1
  • 8
  • 19
1

Give them all a common class and access using document.getElementsByClassName('class').

n_n
  • 141
  • 8
1

IDs should be unique for each element. You could use document.getElementsByClassName or document.querySelectorAll(".class"); and then use the class name (assuming relatively modern browser). Or use document.getElementsByTagName() and then iterate through the elements comparing with the class.

acarlon
  • 16,764
  • 7
  • 75
  • 94
0

Attach a jQuery lib and you will be able to do something like:

$('input[type=text]').each(function(i, val){
    alert($(this).val());
});
ArVan
  • 4,225
  • 8
  • 36
  • 58