我如何获得标签数量

时间:2019-06-19 12:53:33

标签: javascript jquery html

我有多个输入字段,每个输入均包含逗号分隔的值

<input type="text" class="form-control tags tokenfield" name="variant[value]" value="red,blue,green">

我有很多标签输入类,每个输入包含可变数量的tags。如何遍历输入并获取使用jQuery的标签总数?

$('.tags').on('change', function(event){
    for(i = 0; i < $('.tags').length; i++){
        // Stuck here - not sure what to do
    }
});

我如何基于像这样的元素创建选项表: enter image description here

2 个答案:

答案 0 :(得分:2)

当您遍历每个输入的值时,请使用.split()方法以逗号分隔字符串并计算结果数组中的项数:

$('.tags').on('change', function(event){
  $('.tags').each(function(index, element){
    console.log("Input " + (index + 1) + " has " + element.value.split(",").length + " items in it.");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control tags tokenfield" name="variant[value]" value="red,blue,green">
<input type="text" class="form-control tags tokenfield" name="variant[value]" value="red,blue,green,yellow">
<input type="text" class="form-control tags tokenfield" name="variant[value]" value="red,blue,green,orange, brown">
<input type="text" class="form-control tags tokenfield" name="variant[value]" value="red,blue">

答案 1 :(得分:0)

在每个逗号处收集.val() .each()$('.tag')中的.split()。每个输入都会添加一个值数组,使用.flat()可以是一个数组。要获取总数,请使用.length

var tags = [];
$('.tag').each(function() {
  var str = $(this).val();
  var arr = str.split(',');
  tags.push(arr);
});
var tagValues = tags.flat();
console.log(JSON.stringify(tagValues));
console.log("Total number: "+tagValues.length)
<input class='tag' value='1,2,3'>
<input class='tag' value='red,blue,yellow'> 
<input class='tag' value='Monday,Tuesday,Wednesday'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

相关问题