Concatenate in loop with jQuery

Asked

Viewed 384 times

3

I need to concatenate with jQuery all input values that have classes that start with "item_". I’m using the function below but it didn’t work.

$(document).ready(function() {
 $('button.vai').click(function(){
  var item = $("input[class^='item_']").val();
   for(i=0,i<item.length,i++) {
    item += item + "#";
   }
  $(".result").val(item);
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p><button class="vai">concatena tudo!</button></p>

<input type="text" class="item_1" value="valor1"><br>
<input type="text" class="item_2" value="valor2"><br>
<input type="text" class="item_3" value="valor3"><br>
<input type="text" class="item_4" value="valor4"><br>
<input type="text" class="itemfalso" value="valor5"><br>
<p><input type="text" class="result" value=""></p>

I hope to get a result like the following that is in quotes: "value1#value2#value3#value4". Regardless of the "extension" I put in item_vagueness and the amount of fields that contain this class I want to concatenate their values to form a single string.

  • Man, that line var item = $("input[class^='item_']").val(); I suspect you did to take all the values of inputs where class = item_X. But he’s only taking the value of the first class.

  • Thanks Jeferson, I’ll go over the code.

1 answer

3


You can keep your selector as is and use the functions .map() to generate its array of values, and the function .join('#') to concatenate array positions with the string # as the example below:

$('button.vai').click(function () {

    var arrayValor = $("input[class^='item']").map(function () {
        return this.value;
    }).get().join('#');

    $('.result').val(arrayValor);
});

Follows jsfiddle =D

  • 1

    Perfect Brunno, that’s what I needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.