Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - How to concatenate text with .each?

First of all, excuse me for my bad english.

I've tried various methods but haven't had any luck as of yet.

I'm returning a series of objects with .each()method.

I'd like to populate the "value" attribute of a input field with each value from the object. I didnt find a way to do the same thing as PHP .=

Any idea would be great!

Here's my code :

$.each($("input[type='checkbox']:checked"), function(){
        var data = $(this).parent().parent().find("td:eq(1)"); 
         $("#login").val(data.text());
    })
like image 542
skytorner Avatar asked Feb 13 '13 09:02

skytorner


2 Answers

var c = '';
$.each($("input[type='checkbox']:checked"), function(){
    var data = $(this).parent().parent().find("td:eq(1)"); 
    c += data.text();
})
$("#login").val(c);

You could also have used this in the loop :

$("#login").val($("#login").val(c)+data.text());

but I personally prefer to minimize the changes of the DOM.

Note also that using traversals like parent().parent() lead to maintenance problems. In your case you could probably use

var data = $(this).closest('tr').find("td:eq(1)"); 

so that the code won't break if a span or any other elements wraps your input in the future.

like image 53
Denys Séguret Avatar answered Oct 05 '22 10:10

Denys Séguret


You can use map(). You can pass the delimiter character to join() to separate the alues.

text = $("input[type='checkbox']:checked").map( function(){
    return $(this).parent().parent().find("td:eq(1)");        
}).get().join();

$("#login").val(text);
like image 23
Adil Avatar answered Oct 05 '22 08:10

Adil