0

How is the "check" made for this to check if a textfield is empty?

Jquery:

$("#AddGoogleMap").click(function () {      
    if($('#googleMapCity').val()==null) {
        alert("You need to fill out a city");
    } else {
     // do something
    }
4
  • $('#googleMapCity').val()==='' or $('#googleMapCity').val().length===0 Commented May 16, 2013 at 13:27
  • Did you search ? I can't think the question I linked or similar ones wasn't listed when you typed your question. Commented May 16, 2013 at 13:28
  • 1
    @HamZaDzCyberDeV: .empty() removes the content and any nested DOM element. Commented May 16, 2013 at 13:28
  • @kiddorails Sorry ^^' Commented May 16, 2013 at 13:29

5 Answers 5

3

First, remove the whitespace from the beginning and end of a string and then compare the value with the empty string, like:

if( $.trim($('#googleMapCity').val()) === '') {
     alert("You need to fill out a city");
} else {
 // do something
}
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for suggesting best practice of trimming in case of empty space
Nice! Thanks! But the thing is it fires even though I fill out something in the field, does it need to be a rule for the "else"?
@Kim: This fiddle might help you! Try it once.
1
if($('#googleMapCity').val() === "") {
 alert("You need to fill out a city");
}

Comments

1

Could be done like this:

if($.trim($('#googleMapCity').val())==="")

Comments

1
 $("#AddGoogleMap").click(function () {      
    if($('#googleMapCity').val()==='') {
    alert('You need to fill out a city');

     } else {
     // do something
     }

Comments

1

Working Demo

$("#AddGoogleMap").click(function () {      
    if($('#googleMapCity').val() === "") {
        alert("You need to fill out a city");
     } else {
     // do something
     }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.