I have a form that I would like all fields to be filled in. If a field is clicked into and then not filled out, I would like to display a red background.
Here is my
$(function() {
var fields = $('#search_form').serializeArray();
is_blank = true;
for (var i = 0; i < fields.length; i++) {
// excluded fields
if ((fields[i].name != "locale") && (fields[i].name != "utf8")) {
if (fields[i].value) {
is_blank = false;
}
}
}
if (is_blank) {
$('#filters-button').append(': OFF');
}
else {
$('#filters-button').append(': ON');
}
});
Check if all fields are empty and append ON or OFF on Filter_button
how come nobody mentioned
$(this).filter('[value=]').addClass('warning');
seems more jquery-like to me
function checkForm() {
return $('input[type=text]').filter(function () {
return $(this).val().length === 0;
}).length;
}
<script type="text/javascript">
$('input:text, input:password, textarea').blur(function()
{
var check = $(this).val();
if(check == '')
{
$(this).parent().addClass('ym-error');
}
else
{
$(this).parent().removeClass('ym-error');
}
});
</script>// :)
The :empty
pseudo-selector is used to see if an element contains no childs, you should check the value :
$('#apply-form input').blur(function() {
if(!this.value) { // zero-length string
$(this).parents('p').addClass('warning');
}
});
Great collection of answers, would like to add that you can also do this using the :placeholder-shown
CSS selector. A little cleaner to use IMO, especially if you're already using jQ and have placeholders on your inputs.
if ($('input#cust-descrip').is(':placeholder-shown')) {
console.log('Empty');
}
$('input#cust-descrip').on('blur', '', function(ev) {
if (!$('input#cust-descrip').is(':placeholder-shown')) {
console.log('Has Text!');
}
else {
console.log('Empty!');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" id="cust-descrip" autocomplete="off" placeholder="Description">
You can also make use of the :valid
and :invalid
selectors if you have inputs that are required. You can use these selectors if you are using the required attribute on an input.