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.

2
  • 1
    Id must be unigue. You cant have multiple items with the same Id Commented Feb 3, 2014 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 stackoverflow.com/questions/1933602/… Commented Feb 3, 2014 at 10:22

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I like and have used this solution :)
1

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

Comments

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.

Comments

0

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

$('input[type=text]').each(function(i, val){
    alert($(this).val());
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.