19

I have an input that I want to validate:

<input type="text" id="input" />

And here's the JS:

        jQuery("#input").live('change', function() {

            if("#input:not(:empty)") {
                alert('not empty');
            }   

            else if("#input:empty") {
                alert('empty'); 
            }
        });

Even when the "#input" is empty there's no way of displaying alert with "empty" message. So, basically, no matter what I do, only the first statement is true and the second is false, always.

What's wrong?

Wordpressor
  • 7,173
  • 23
  • 69
  • 108
  • Possible duplicate of [Check if inputs are empty using jQuery](http://stackoverflow.com/questions/1854556/check-if-inputs-are-empty-using-jquery) – The Codesee Mar 09 '17 at 19:22

4 Answers4

32

JQuery's :empty selector selects all elements on the page that are empty in the sense that they have no child elements, including text nodes, not all inputs that have no text in them.

Jquery: How to check if an input element has not been filled in.

Here's the code stolen from the above thread:

$('#apply-form input').blur(function()          //whenever you click off an input element
{                   
    if( !$(this).val() ) {                      //if it is blank. 
         alert('empty');    
    }
});

This works because an empty string in JavaScript is a 'falsy value', which basically means if you try to use it as a boolean value it will always evaluate to false. If you want, you can change the conditional to $(this).val() === '' for added clarity. :D

Community
  • 1
  • 1
Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
6

You could do this

$("#input").blur(function(){
    if($(this).val() == ''){
        alert('empty'); 
    }
});

http://jsfiddle.net/jasongennaro/Y5P9k/1/

When the input has lost focus that is .blur(), then check the value of the #input.

If it is empty == '' then trigger the alert.

Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86
2

Actually there is a simpler way to do this, just:

if ($("#input").is(':empty')) {
console.log('empty');
} else {
console.log('not empty');
}

src: https://www.geeksforgeeks.org/how-to-check-an-html-element-is-empty-using-jquery/

N.Tec
  • 127
  • 2
  • 13
Mcloide
  • 422
  • 5
  • 16
2
    jQuery("#input").live('change', function() {
        // since we check more than once against the value, place it in a var.
        var inputvalue = $("#input").attr("value");

        // if it's value **IS NOT** ""
        if(inputvalue !== "") {
            jQuery(this).css('outline', 'solid 1px red'); 
        }   

        // else if it's value **IS** ""
        else if(inputvalue === "") {
            alert('empty'); 
        }

    });
Willem
  • 723
  • 2
  • 9
  • 27