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
2 Answers
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);
});