简体   繁体   English

jQuery:计算具有特定值的输入数

[英]jQuery: Count Number of Inputs with a Specific Value

I need to count the number of text inputs with a value of 1. 我需要计算值为1的文本输入数。

I have tried the following but with no luck. 我尝试过以下但没有运气。

$('.class[value="1"]').length
$('.class:contains("1")').length

Using $('.class[value="1"]') technically works, however, if the values in the text input are changed after load, it still counts it as its default load value. 但是,使用$('.class[value="1"]')技术上有效,如果文本输入中的值在加载后更改,它仍将其计为默认加载值。

I took a long shot by using the .live click event to get the current value but still no luck. 我通过使用.live点击事件来获取当前值,但仍然没有运气。

I had no luck at all using $('.class:contains("1")') 我没有运气使用$('.class:contains("1")')

It seems very simple, but has so far eluded me. 这似乎很简单,但到目前为止还没有找到我。

This example demonstrates that this works: 此示例演示了这有效:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
  $("#btn").click(function() {
    alert($(":input[value='1']").length);
  });
});
</script>
</head>
<body>
<input type="text">
<input type="text">
<input type="text">
<input type="button" id="btn" value="How many?">
</body>
</html>

Alternatively you can just loop: 或者你可以循环:

var matches = 0;
$(":input.class").each(function(i, val) {
  if ($(this).val() == '1') {
    matches++;
  }
});

You need to iterate with $.each() if you want current val() values: 如果你想要当前的val()值,你需要使用$ .each()进行迭代:

k=0;
$('.class').each(function(i, e) {
  if ($(e).val() == "1") k++;
});
$(':input.class').filter(function() {
    return $(this).val() == '1'
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM