Concatenate in loop with jQuery

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 did not 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><buttonclass="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 expect to get a result like the following that is enclosed in quotation marks: "value1 # value2 # value3 # value4". Regardless of the "extension" I put in item_ myextension and the amount of fields that contain this class I want to concatenate their values to form a single string.

    
asked by anonymous 17.09.2015 / 03:54

1 answer

3

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

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

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

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

Follow jsfiddle = D

    
17.09.2015 / 05:30