Get all span text with jquery?

时间:2018-03-25 20:53:03

标签: jquery each

<div id="product">
<span class="tag">lorem ipsum<span class="remove"></span></span>
<span class="tag">lorem ipsum<span class="remove"></span></span>
<input type="hidden" id="selected-value" value="">
</div>

İ want get all span text and paste to hidden input with jQuery. Like this:

<input type="hidden" id="selected-value" value="lorem ipsum,lorem ipsum">

Post data : 'lorem ipsum,lorem ipsum'

I did try this code but not working:

$( "#product span" ).each(function( index ) {
      $('#selected-value').val("," + $( this ).text());
});

4 个答案:

答案 0 :(得分:0)

Change te #product span to $(".tag")

Like this:

$( ".tag" ).each(function( index, value ) {
      var oldInputs = $("#selected-value").val();
      $('#selected-value').val(oldInputs +"," $(this).val());
});

答案 1 :(得分:0)

First loop through all the spans and extract what you want. Finally use that result as you want.

$(document).ready(function(){
  var textvalues = [];
  $( "#product>span" ).each(function() {
      textvalues.push($( this ).text())
  });

  $('#selected-value').val(textvalues.join(","));
});

答案 2 :(得分:0)

You said you need ALL span text, well, here it is, although maybe you meant only span.tag and leave out the emptiness of span.remove, in that case just add .tag to the selector

var texts = [];
$( "#product span" ).each(function( index ) {
if($(this).text().match(/ +/, false))
      texts.push($( this ).text());
});
$('#selected-value').val(texts.join(', '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product">
<span class="tag">lorem ipsum1<span class="remove"></span></span>
<span class="tag">lorem ipsum2<span class="remove"></span></span>
<input type="hidden" id="selected-value" value="">
</div>

答案 3 :(得分:0)

另一种方法,因为为什么不:

var output = $('span')
  .toArray()              // so we can use filter and map
  .map(function(e) {      // get the text contents instead of the whole node
    return $(e).text()
  })
  .filter(Boolean)        // drop empty elements from the array
  .join(", ");            // Join into a comma-separated string

console.log(output)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product">
  <span class="tag">lorem ipsum<span class="remove"></span></span>
  <span class="tag">lorem ipsum<span class="remove"></span></span>
  <input type="hidden" id="selected-value" value="">
</div>