jpsear
jpsear

Reputation: 43

Loop through multiple inputs and save the answer to a variable using jQuery

So far, I have:

$('.the-inputs input').each(function() {
    userAnswer = $(this).val();
});

However, if I console.log this out, it comes out on separate lines (is this an array?) I would like it as a string.

So, if the user enters "Hello" "World" in the two inputs, I want the variable userAnswer = "Hello World".

I also need the variable accessible outside the function. Am I right in leaving off the var to achieve this?

Upvotes: 0

Views: 403

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388326

You can use .map() to solve this:

var userAnswer = $('.the-inputs input').map(function() {
    return $(this).val();
}).get().join(' ');

Upvotes: 6

Artek Wisniewski
Artek Wisniewski

Reputation: 797

var userAnswer = '';

$('.the-inputs input').each(function() {
 userAnswer += $(this).val() + ' '; // add to string
});

userAnswer = $.trim(userAnswer);

console.log(userAnswer);

Upvotes: 1

Related Questions