Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - simple input validation - "empty" and "not empty"

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?

like image 306
Wordpressor Avatar asked Jul 23 '11 15:07

Wordpressor


People also ask

How check input field is empty or not in jQuery?

To check if the input text box is empty using jQuery, you can use the . val() method. It returns the value of a form element and undefined on an empty collection.

How can check input value is number or not in jQuery?

version added: 1.7jQuery. The $. isNumeric() method checks whether its argument represents a numeric value. If so, it returns true . Otherwise it returns false .

Is Empty jQuery?

jQuery empty() MethodThe empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method.


1 Answers

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

like image 61
Gordon Gustafson Avatar answered Sep 20 '22 20:09

Gordon Gustafson