Tom Mesgert
Tom Mesgert

Reputation: 1311

jquery - add to array

Why this not working?

var inputs = new Array();
$("input").each(function(){
    input = $(this).val();
})

console.log(input);

how to correctly use arrays in jQuery? Like as PHP?

Upvotes: 0

Views: 4998

Answers (2)

Lix
Lix

Reputation: 47966

I assume what you are trying to do is get an array of the values of all the <input> elements on your page. What you'll need to do is iterate over all the elements using the .each() function and append each value to your inputs array.

Try this -

 var inputs = new Array();
  $("input").each(function(){
      inputs.push($(this).val());
  })

  console.log(inputs);

You need to use the push() function to add an element to an array.

fiddle demo


References -


As a final note, here is a shorthand way to define a new array -

var inputs = [];

That line is functionally identical to -

var inputs = new Array();

Upvotes: 2

Manse
Manse

Reputation: 38147

Use Array.push

var inputs = new Array();
$("input").each(function(){
   inputs.push($(this).val());
})

Also note the variable differences .. input != inputs

Upvotes: 2

Related Questions