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.
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.
Share asked Apr 7, 2014 at 15:58 puactionpuaction 2113 silver badges12 bronze badges 6-
2
Please show us the code for
isEmpty
... it's not a built in function. It might be expecting the value ofinput.user
rather than the jQuery object, so you could tryisEmpty($('input.user').val())
. – Matt Commented Apr 7, 2014 at 15:59 -
$('input.user').val() === ""
or$('input.user').val().length === 0
– blgt Commented Apr 7, 2014 at 16:00 - 1 stackoverflow./questions/4597900/… – Blazemonger Commented Apr 7, 2014 at 16:00
- This is just a simple <input name=user type=text> – puaction Commented Apr 7, 2014 at 16:00
- @blgt yes i know this method and it was working for me but i was looking for cleaner method that is why i asked – puaction Commented Apr 7, 2014 at 16:01
4 Answers
Reset to default 6In 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.
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){ }
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/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
}
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.