Forum Moderators: open

Message Too Old, No Replies

Select an empty field - Jquery

         

rwilson

12:45 am on Sep 25, 2010 (gmt 0)

10+ Year Member



Hi, I am trying to select an input that has nothing in it, so far I think I'm doing it backwards.
I think with
!=''
I am saying is NOT equal to an empty.

What would be the correct way to say it is equal?

Here's my code

$("#search").mouseout(function(){
if ($("#search").val() = '') {
$("#searchLabel").fadeIn();
$("#search").blur();
}
});


Any help is greatly appreciated!

Fotiman

3:28 am on Sep 25, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



if ($("#search").val() = '') {

Lets break it down from inside out:

$("#search")
jQuery will get the element with the id of "search"

$("#search").val()
jQuery will get the element with the id of "search" and get the value of that element.

$("#search").val() = ''
jQuery will get the element with the id of "search" and get the value of that element, and then you're using the ASSIGNMENT operator (=) incorrectly. You want to test for equality, which is TWO equal signs (==).

So to correct your code, you need only add another equal sign:
if ($("#search").val() == '') {

Query will get the element with the id of "search" and get the value of that element, and then compare that value with an empty string.

One thing to note... if the value of the input contains whitespace (ie - the user hit the spacebar in the field), then the above example will not evaluate to true. What you probably want to do is trim off any leading or trailing whitespace before doing the comparison. Fortunately, jQuery has a method for that:

if ($.trim($("#search").val()) == '') {

Hope that helps.

rwilson

2:36 pm on Sep 25, 2010 (gmt 0)

10+ Year Member



Thank you so much for everything, breaking it down and showing me .trim!