简体   繁体   English

如何计算页面上值的输入总数?

[英]How can I count the total number of inputs with values on a page?

I'm hoping for a super simple validation script that matches total inputs on a form to total inputs with values on a form. 我希望有一个超级简单的验证脚本,它将表单上的总输入与表单上的值的总输入相匹配。 Can you help explain why the following doesn't work, and suggest a working solution? 你能帮忙解释为什么以下不起作用,并建议一个有效的解决方案吗?

Fiddle: http://jsfiddle.net/d7DDu/ 小提琴: http//jsfiddle.net/d7DDu/

Fill out one or more of the inputs and click "submit". 填写一个或多个输入,然后单击“提交”。 I want to see the number of filled out inputs as the result. 我希望看到填充输入的数量作为结果。 So far it only shows 0 . 到目前为止它只显示0

HTML: HTML:

<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<textarea name="four"></textarea>
<button id="btn-submit">Submit</button>
<div id="count"></div>

JS: JS:

$('#btn-submit').bind('click', function() {
    var filledInputs = $(':input[value]').length;
    $('#count').html(filledInputs);
});

[value] refers to the value attribute , which is very different to the value property . [value]指的是数值属性 ,它是到值属性有很大不同。

The property is updated as you type, the attribute stays the same. 键入时属性会更新,属性保持不变。 This means you can do elem.value = elem.getAttribute("value") to "reset" a form element, by the way. 这意味着您可以执行elem.value = elem.getAttribute("value")来“重置”表单元素。

Personally, I'd do something like this: 就个人而言,我会做这样的事情:

var filledInputs = $(':input').filter(function() {return !!this.value;}).length;

Try this: http://jsfiddle.net/justincook/d7DDu/1/ 试试这个: http//jsfiddle.net/justincook/d7DDu/1/

$('#btn-submit').bind('click', function() {
    var x = 0;
    $(':input').each(function(){
        if(this.value.length > 0){ x++; };
    });
    $('#count').html(x);
});

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

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