Reputation: 43
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
Reputation: 388326
You can use .map() to solve this:
var userAnswer = $('.the-inputs input').map(function() {
return $(this).val();
}).get().join(' ');
Upvotes: 6
Reputation: 797
var userAnswer = '';
$('.the-inputs input').each(function() {
userAnswer += $(this).val() + ' '; // add to string
});
userAnswer = $.trim(userAnswer);
console.log(userAnswer);
Upvotes: 1