0

Why this jQuery if statment is not working ?

if (isEmpty($('input.user'))) {
    alert ('123123');
}

This is reffering to input box with class of .user so basically if user left it empty alert.

Very basic but not working.

puaction
  • 181
  • 2
  • 12

4 Answers4

6

In jquery if you want to check if a form input is empty you can do it in this way:

if ( ! $('input.user').val()) {
    alert ('123123');
}

The method .val() will return false if the input element is empty.

gpopoteur
  • 1,509
  • 10
  • 18
4

Use .is() and :empty

if ($('input.user').is(':empty')){
     alert ('I am Empty'); // alert ('123123');
}


if ($('input.user').val() === ''){ }


Or
if ($.trim($('input.user').val()) === ''){ }


Or
if ($.trim($('input.user').val()).length === 0){ }
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
1

There is no built-in JavaScript function for isEmpty.

If you want to check if a field is empty using jQuery you should use something like:

if (!$('input.user').val()){
   // DO SOMETHING
   alert ('123123');
}

Here's a jsFiddle that shows you how to check if a value is present on clicking a button - http://jsfiddle.net/jEte6/

To do the same using pure Javascript (No libraries)

If you're testing for an empty string:

if(myVar === ''){
    // Do something
}

If you're checking for a variable that has been declared, but not defined:

if(myVar === null){
    // Do something
}

If you're checking for a variable that may not be defined:

if(myVar === undefined){ 
    // Do something
}
ajtrichards
  • 29,723
  • 13
  • 94
  • 101
0

In my case, the problem was that I was including jQuery twice in my html. Check your html and if there are two, delete one and the problem should be fixed.

lwdthe1
  • 1,001
  • 1
  • 16
  • 16