1

The following code executes on the press of a button. It works fine alerting one string of the getElementsByName array, but when introduced to a loop, it still only alerts the first string value, and nothing more:

function checkvals() {

var input = document.getElementsByName('ModuleTitle', 'ModuleCode', 'BuildingName', 'Day');
var i = 0;

for (i = 0; i <= input.length; i++){
alert(input[i].value);
}
}

2 Answers 2

3

That's because getElementsByName only accepts one argument, so it's only fetching the first name.

You can build a full collection like this...

var names = ['ModuleTitle', 'ModuleCode', 'BuildingName', 'Day'];

var input = [];
for(var i = 0; i < names.length; i++) {
    var name_els = document.getElementsByName(names[i]);
    for(var j = 0; j < name_els.length; j++) {
        input.push(name_els[j]);
    }
}

Then loop over the input Array, (or just do your work in the inner loop).


Additionally, you have a bug.

This...

for (i = 0; i <= input.length; i++){

should be this...

for (i = 0; i < input.length; i++){

...otherwise, you'll go one past the last index.

Sign up to request clarification or add additional context in comments.

Comments

0

That's because getElementsByName only takes a single name argument, and returns all elements with that value for their name attribute. (See https://developer.mozilla.org/en/DOM/document.getElementsByName.) If you have multiple names to look up, you'll have to call it multiple times.

1 Comment

But it still only alerts one value even when I do this: function checkvals() { var input = document.getElementsByName('ModuleTitle', 'ModuleCode', 'BuildingName', 'Day'); alert(input[0].value); alert(input[1].value); alert(input[2].value); alert(input[3].value); }

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.