A K
A K

Reputation: 23

populating form fields with array

How can I take a array values and populate already existing text fields. For an example, array would have 5 values and there would be 5 text fields.

Array [ tom, Matt, Lucy, Suzanna, Hank ]
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">

Upvotes: 0

Views: 2499

Answers (3)

Rion Williams
Rion Williams

Reputation: 76547

You should be able to use something like the following to iterate through your <input> elements and pop off each name until they have each been exhausted :

// Your array
var array = ['Tom', 'Matt', 'Lucy', 'Suzanna', 'Hank'];

// Loop through the array and target the next available textbox
for(var input in document.getElementsByName('firstName')){
    // If there are any names to use, use one
    if(array.length > 0){
       // Pop the next name off of your array and set the value
       // of your textbox
       input.value = array.pop();
    }
}

If you have any issues actually using the above example to set the values, you can always use a slightly different loop to handle things :

// Your array
var array = ['Tom', 'Matt', 'Lucy', 'Suzanna', 'Hank'];

// Store your input elements
var inputs = document.getElementsByName('firstName');
// Loop through the array and target the next available textbox
for(var i = 0; i < inputs.length; i++){
        // If there are any names to use, use one
        if(array.length > 0){
           // Pop the next name off of your array and set the value
           // of your textbox
           inputs[i].value = array.pop();
        }
}

You can see a working example in action here and what the output using the data you provided might look like below :

enter image description here

Upvotes: 1

Hugo S. Mendes
Hugo S. Mendes

Reputation: 1086

you can do that in a bunch of different ways. e.g

give the fields a class and use jquery to add the value to them

<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">

then you can use jquery or javascript to add the value to them:

var currIndex = 0;
$(document).ready(function(){
    $(".damn").each(function(){
        $(this).val(myarray[currIndex++]);
    });
});

UPDATE: You can also use the approach created by Rion Williams up there.

Upvotes: 0

Nbert.
Nbert.

Reputation: 143

You could iterate over the array as a whole, or just simply access every array value one by one

Upvotes: 0

Related Questions