最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I count the total number of inputs with values on a page? - Stack Overflow

programmeradmin5浏览0评论

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: /

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.

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:

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

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/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.

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:

$('#btn-submit').bind('click', function() {
    var filledInputs = $(':input[value]').length;
    $('#count').html(filledInputs);
});
Share Improve this question asked May 19, 2013 at 3:27 RyanRyan 15.3k34 gold badges116 silver badges190 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

[value] refers to the value attribute, which is very different to the value property.

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.

Personally, I'd do something like this:

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

Try this: http://jsfiddle/justincook/d7DDu/1/

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

评论列表(0)

  1. 暂无评论