Reputation: 3
i have 20 text boxes Firstname, lastname, email etc... i want to make an object of these text boxes values using for loop.
var object = {};
for (var x = 0; x; x++) {
this is what i am trying to get as result:
Object {name: "gill", lastname: "bill", email: "[email protected]"}
Upvotes: 0
Views: 76
Reputation: 141827
var inputs = ...;
var obj = {};
for ( var i = 0; i < inputs.length; i++ )
obj[inputs[i].name] = inputs[i].value;
How you fill in the ...
depends on how your inputs are defined in your HTML and how you want to group them. If you want to select all the inputs on the page, you could use
var inputs = document.getElementsByTagName( 'input' );
but that could give you weird behaviour if you ever add another input like a search bar to your page.
If all your fields are contained within some ancestor element with an id you could use:
var inputs = document
.getElementById( 'ancestorId' )
.getElementsByTagName( 'input' )
;
Upvotes: 1