The script below is used to hide a paragraph until all text fields inside div.form have been filled out.
As it is now, in order to reveal the paragraphs I would have to fill out BOTH forms. What I want is for each form to act independently. In other words, if you filled out the three inputs in the first form, the paragraph in that first DIV would be revealed.
I can accomplish this by duplicating the code and adding more classes, but that is obviously less than ideal.
HTML
<div class="form one">
<input type="text" />
<input type="text" />
<input type="text" />
<p style="display:none">All inputs in this DIV contain text</p>
</div>
<div class="form two">
<input type="text" />
<input type="text" />
<input type="text" />
<p style="display:none">All inputs in this DIV contain text</p>
</div>
jQuery
$('.form input').keyup(function() {
var empty = false;
$('.form input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('.form p').css('display', 'none');
} else {
$('.form p').css('display', 'block');
}
});
You should simply select the
inputs and thepfrom that.form:And here’s the fiddle: http://jsfiddle.net/tGBGK/
P.S. You could further optimize this by caching the selectors.
Alternatively, you could forego the loop, and just use an attribute selector:
…and here’s the fiddle: http://jsfiddle.net/tGBGK/1/
You can further shorten this, by using a ternary operator:
…and finally, here’s the fiddle: http://jsfiddle.net/tGBGK/2/
Thanks @JesseB.