Daniel.P.
Daniel.P.

Reputation: 480

jQuery use each function on html inputs

Hi I've tried to write JavaScript (jQuery) function to merge values from input type text.

My code

$('#addpoll').click(function () {
    var answers = $('#answertable').find('input[type=text]');
    var answersStream = '';

    $.each(answers, function(index, value) {
        answersStream=answersStream.val()+value+'#';
    });

    alert(answersStream);
});

So there is html code

<table id="answertable">
    <tr><td>1]</td><td><input type="text" name="answer1" id="answer1" style="width:300px" /></td></tr>
    <tr><td>2]</td><td><input type="text" name="answer2" id="answer2" style="width:300px" /></td></tr>
</table>

Answers are added by jQuery dynamically, so there could by N answers

I want output in variable answersStream like: yes#no#undefine

But function each doesn't work like that. Function goes through objects but it cant't receive values.

Upvotes: 0

Views: 394

Answers (4)

Matthew Cox
Matthew Cox

Reputation: 13672

$('#addpoll').click(function () 
{
     var answers = $('#answertable').find('input[type=text]');
     var answerStream = []; //use an array for string concatenation

     answers.each(function() 
     {
         answerStream.push($(this).val());
         answerStream.push('#');
     });
     var result = answerStream.join('');
     result = result.substring(0. result.length - 2); //trim trailing # symbol
});

EDIT: this each() function is inheritantly slower than accessing the elements yourself like this:

$('#addpoll').click(function () 
{
     var answers = $('#answertable').find('input[type=text]');
     var answerStream = []; //use an array for string concatenation

     for(var i = 0; i < answers[0].length; i++)
     {
         answerStream.push($(answers[i]).val());
         answerStream.push('#');
     });
     var result = answerStream.join('');
     result = result.substring(0. result.length - 2); //trim trailing # symbol
});

Upvotes: 2

comu
comu

Reputation: 921

var answerStream = new array();
$('#addpoll').click(function () {
    $("#answertable input[type='text']").each(function(){
       var a=$(this).val()+"#";
       answerStream.push(a);                                                        
    });
});

Makes an ARRAY called answer steam. Pushes the results to it. Not sure what you are trying to accomplish but should work

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816324

You could use .map() [docs] to create an array of values and then join [docs] them:

var answersStream = $('#answertable input[type="text"]').map(function() {
     return this.value;
}).get().join('#');

Upvotes: 4

Clive
Clive

Reputation: 36957

answersStream is a string variable but you're trying to use it like a jQuery object (by calling val() on it). It should be as simple as this to do:

answersStream += value.val() + '#';

The value argument will be the jQuery object so you should call val() on that instead

Upvotes: 3

Related Questions