Reputation: 2079
i have several input fields with a class name of required
.
i have a code below to check if all my <input>
fields have a value, if not empty or null, it will show/unhide a specific div
.
but it doest seem to work on me.
also, by default, #print
is displayed as none via CSS.
<!-- index.php -->
<input type="text" id="getID" class="required form-control" placeholder="id">
<input type="text" id="getName" class="required form-control" placeholder="name">
<!-- script.js -->
$(document).ready(function() {
$('input.required').each(function() {
if($(this).val() != "") {
$("#print").show();
}
else {
$("#print").hide();
}
});
});
Upvotes: 0
Views: 5543
Reputation: 253318
I'd suggest:
$('#print').toggle(!($('input.required').length == $('input.required').filter(function () {
return this.value;
}).length));
Obviously this should be run on submit
, assuming you want to only show the #print
element as a validation prior to submission.
References:
Upvotes: 2
Reputation: 4765
As I stated in my comment above, you're checking the values when the page loads, before the user has any chance to enter anything. If you have a button on your page, bind the event to that which will fire the function at the right time.
Something a little like this jFiddle
index.php
<input type="text" id="getID" class="required form-control" placeholder="id">
<input type="text" id="getName" class="required form-control" placeholder="name">
<div id="button">Submit</div>
<div id="print">You're missing something D:!</div>
script.js
$('#button').on('click', function() {
$('#print').hide();
var error=false;
$('input.required').each(function() {
if($(this).val() == "") {
error=true;
}
});
if(error) {
$('#print').show();
}
});
Upvotes: 1
Reputation: 388316
Try
$(document).ready(function () {
//the default state
var valid = true;
$('input.required').each(function () {
//if the value of the current input is blank then the set is invalid and we can stop the iteration now
if ($.trim(this.value) == '') {
valid = false;
return false;
}
});
//set the visibility of the element based on the value of valid state
$("#print").toggle(!valid);
});
Upvotes: 0