0

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?

9
  • 1
    Arrays are part of native JavaScript, there's no special jQuery syntax for them. However, your code shows a total lack of understanding of basic programming concepts, so I'd suggest you go back and cover those. Commented Aug 7, 2012 at 11:11
  • what do you want to do exactly? Commented Aug 7, 2012 at 11:12
  • the array needs an index . eg input[0] = $(this).val(); Commented Aug 7, 2012 at 11:12
  • @AnthonyGrist he is asking a question because he doesn't know to do it. Commented Aug 7, 2012 at 11:13
  • 2
    @Raminson He's asking a question that he shouldn't need to ask if he'd covered the basic concepts of programming in JavaScript. There are plenty of well-written guides covering them to be found in less than a minute on Google. There's no research effort on his part (criteria for downvoting) and the question isn't going to be useful to anybody else (criteria for closing as too localized). Commented Aug 7, 2012 at 11:34

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Technically input = $(this).val(); will define the variable on the global scope.
2

Use Array.push

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

Also note the variable differences .. input != inputs

1 Comment

But I think this is more constructive. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.