当在输入字段中输入一个值时,我想计算该行中总共有多少个输入字段有一个值。
<div class="row">
<input type="text" class="input input1" />
<input type="text" class="input input2" />
<input type="text" class="input input2" />
</div>
<div class="row">
<input type="text" class="input input1" />
<input type="text" class="input input2" />
<input type="text" class="input input2" />
</div>
我正在尝试跟随,但我认为问题出在循环上。
$('.input').keyup(function () {
var field = $(this).parent().children('.input');
var count = 0;
$(field).each(function (i) {
var len = $(field).val().length;
if (len > 0 ) {
count++;
}
});
alert(count);
});
JSFiddle 链接:http://jsfiddle.net/18cpotw6/
最佳答案
使用 $(field).val()
,您将检索 field
jQuery 集合中的 first 元素的值。使用 $(this).val()
代替:
$('.input').keyup(function() {
var field = $(this).parent().children('.input');
var count = 0;
$(field).each(function() {
if ($(this).val()) {
count++;
}
});
console.log(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<input type="text" class="input input1" />
<input type="text" class="input input2" />
<input type="text" class="input input2" />
</div>
<div class="row">
<input type="text" class="input input1" />
<input type="text" class="input input2" />
<input type="text" class="input input2" />
</div>
您还可以删除 i
参数,因为它未被使用。
关于javascript - jQuery 计算具有值的输入字段的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58603502/