0

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: "gill@abc.com"}
moh
  • 3
  • 2
  • 1
    if you are using jQuery, take a look at this selector: http://stackoverflow.com/questions/10322891/loop-through-all-text-boxes-in-a-form-using-jquery – Josep Valls May 09 '15 at 01:04

1 Answers1

1
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' )
;
Paul
  • 139,544
  • 27
  • 275
  • 264
  • Nice. You could also attach the input's length to a variable so that it is calculated only once, instead of in each loop iteration. It may not add much performance if the length is small, but you never know how things will grow latter on. – bpbutti May 09 '15 at 01:37
  • @bpbutti I doubt it makes any difference. I think the interpreter is smart enough to see that you are not modifying the length inside that loop, and the length property is just a property lookup anyway. It's not like accessing the length property causes the array to be counted. Reading the `length` property is no different than reading any property of any object in Javascript. The `length` property only has special behaviour when it is modified. – Paul May 10 '15 at 01:51
  • Yes, I think you are right. I searched more about it and it doesn't seem to make a difference anymore. Maybe I have been reading some old books of when this was relevant. Engines are smart nowadays and caching the length might somehow make things slower. Even if it helps performance a little bit in some cases, it is so 'little bit' that it is not worth doing. Thanks for the heads up. – bpbutti May 10 '15 at 19:25
  • @bpbutti I think that the equivalent in PHP makes a big difference. The comparative is calling `count( $arr )`, which should be stored in a variable rather than calling it on each iteration. Perhaps that is where you got the idea from? – Paul May 10 '15 at 22:12