Check if inputs are empty using jQuery
JqueryValidationJquery Problem Overview
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 code:
$('#apply-form input').blur(function () {
if ($('input:text').is(":empty")) {
$(this).parents('p').addClass('warning');
}
});
It applies the warning class regardless of the field being filled in or not.
What am I doing wrong?
Jquery Solutions
Solution 1 - Jquery
$('#apply-form input').blur(function()
{
if( !$(this).val() ) {
$(this).parents('p').addClass('warning');
}
});
And you don't necessarily need .length
or see if it's >0
since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#apply-form input').blur(function()
{
if( $(this).val().length === 0 ) {
$(this).parents('p').addClass('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value
.
$('#apply-form input').blur(function()
{
if( !this.value ) {
$(this).parents('p').addClass('warning');
}
});
Also you should take note that $('input:text')
grabs multiple elements, specify a context or use the this
keyword if you just want a reference to a lone element (provided there's one textfield in the context's descendants/children).
Solution 2 - Jquery
Everybody has the right idea, but I like to be a little more explicit and trim the values.
$('#apply-form input').blur(function() {
if(!$.trim(this.value).length) { // zero-length string AFTER a trim
$(this).parents('p').addClass('warning');
}
});
if you dont use .length , then an entry of '0' can get flagged as bad, and an entry of 5 spaces could get marked as ok without the $.trim . Best of Luck.
Solution 3 - Jquery
Doing it on blur is too limited. It assumes there was focus on the form field, so I prefer to do it on submit, and map through the input. After years of dealing with fancy blur, focus, etc. tricks, keeping things simpler will yield more usability where it counts.
$('#signupform').submit(function() {
var errors = 0;
$("#signupform :input").map(function(){
if( !$(this).val() ) {
$(this).parents('td').addClass('warning');
errors++;
} else if ($(this).val()) {
$(this).parents('td').removeClass('warning');
}
});
if(errors > 0){
$('#errorwarn').text("All fields are required");
return false;
}
// do the ajax..
});
Solution 4 - Jquery
if ($('input:text').val().length == 0) {
$(this).parents('p').addClass('warning');
}
Solution 5 - Jquery
you can use also..
$('#apply-form input').blur(function()
{
if( $(this).val() == '' ) {
$(this).parents('p').addClass('warning');
}
});
if you have doubt about spaces,then try..
$('#apply-form input').blur(function()
{
if( $(this).val().trim() == '' ) {
$(this).parents('p').addClass('warning');
}
});
Solution 6 - Jquery
how come nobody mentioned
$(this).filter('[value=]').addClass('warning');
seems more jquery-like to me
Solution 7 - Jquery
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}});
Solution 8 - Jquery
Consider using the jQuery validation plugin instead. It may be slightly overkill for simple required fields, but it mature enough that it handles edge cases you haven't even thought of yet (nor would any of us until we ran into them).
You can tag the required fields with a class of "required", run a $('form').validate() in $(document).ready() and that's all it takes.
It's even hosted on the Microsoft CDN too, for speedy delivery: http://www.asp.net/ajaxlibrary/CDN.ashx
Solution 9 - Jquery
how to check null undefined and empty in jquery
$(document).on('input', '#amt', function(){
let r1;
let r2;
r1 = $("#remittance_amt").val();
if(r1 === undefined || r1 === null || r1 === '')
{
r1 = 0.00;
}
console.log(r1);
});
Solution 10 - Jquery
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');
}
});
Solution 11 - Jquery
There is one other thing you might want to think about, Currently it can only add the warning class if it is empty, how about removing the class again when the form is not empty anymore.
like this:
$('#apply-form input').blur(function()
{
if( !$(this).val() ) {
$(this).parents('p').addClass('warning');
} else if ($(this).val()) {
$(this).parents('p').removeClass('warning');
}
});
Solution 12 - Jquery
function checkForm() {
return $('input[type=text]').filter(function () {
return $(this).val().length === 0;
}).length;
}
Solution 13 - Jquery
Here is an example using keyup for the selected input. It uses a trim as well to make sure that a sequence of just white space characters doesn't trigger a truthy response. This is an example that can be used to begin a search box or something related to that type of functionality.
YourObjNameSpace.yourJqueryInputElement.keyup(function (e){
if($.trim($(this).val())){
// trimmed value is truthy meaning real characters are entered
}else{
// trimmed value is falsey meaning empty input excluding just whitespace characters
}
}
Solution 14 - Jquery
$(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
Solution 15 - Jquery
You can try something like this:
$('#apply-form input[value!=""]').blur(function() {
$(this).parents('p').addClass('warning');
});
It will apply .blur()
event only to the inputs with empty values.
Solution 16 - Jquery
<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>// :)
Solution 17 - Jquery
With HTML 5 we can use a new feature "required" the just add it to the tag which you want to be required like:
<input type='text' required>
Solution 18 - Jquery
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.
Solution 19 - Jquery
A clean CSS-only solution this would be:
input[type="radio"]:read-only {
pointer-events: none;
}
Solution 20 - Jquery
Please use this code for input text
$('#search').on("input",function (e) {
});
Solution 21 - Jquery
if($("#textField").val()!=null)
this work for me
Solution 22 - Jquery
try this:
function empty(){
if ($('.text').val().length == 0)
{
alert("field should not be empty");
}
}