AngelDeLaNoche
AngelDeLaNoche

Reputation: 21

JavaScript reading reading list of form items

I have a form with multiple input fields:

<input name="a1"/>
<input name="a2"/>
<input name="a3"/>

All field names are the same with an added digit.

I need JavaScript to read these values into an array.

for i = 1 to 3
   a(i) = form(i)
next

Complete code:

var listC = [ "C", "A", "B" ]; 
a1 = form.a1.value; 
a2 = form.a2.value;
a3 = form.a3.value; 

if (listC[0] == a1.toUpperCase()) {
    NumCorrect = NumCorrect + 1
}
if (listC[1] == a2.toUpperCase()) {
    NumCorrect = NumCorrect + 1
}
if (listC[2] == a3.toUpperCase()) {
    NumCorrect = NumCorrect + 1
} 

<input type="text" size="2" name="a1" size="2"/>
<input type="text" size="2" name="a2" size="2"/>
<input type="text" size="2" name="a3" size="2"/>

Upvotes: 0

Views: 2759

Answers (3)

Adam Azad
Adam Azad

Reputation: 11297

Not sure if this is what you're after.

var a = [],
    inputs = document.querySelectorAll('[name^="a"]');

[].forEach.call(inputs, function(input){
    a.push(input.value);
});

console.log(a);
<input name="a1" value="a111"/>
<input name="a2" value="a222"/>
<input name="a3" value="a333"/>

Upvotes: 2

J Livengood
J Livengood

Reputation: 2738

Without knowing the form structure you could retrieve it with vanilla javascript as follows:

var arr = [];

var currentElementIndex = 1;
while(document.getElementsByName('a'+currentElementIndex)) {
  arr.push(document.getElementsByName('a'+currentElementIndex).value);
  currentElementIndex++;
}

Assuming id's are >= 1 and sequential.

Upvotes: 0

U.Malik
U.Malik

Reputation: 111

You can do this by adding 'id' attribute similarly 'name' Like,

HTML

<input id="name1" name="name1">  
<input id="name2" name="name2">

Javascript

var formData = [];

for(var i=1 ; i<length; i++){
   formData.push($('#name'+i).val());
}

Upvotes: 0

Related Questions