0

How can I check in jQuery if an input is empty ?

I tried:

$('#location').keydown(function(event) {
  if($("#location").val().length == 0 ) { $("#finalSearch").attr('disabled', 'true'); }
  if($("#location").val().length != 0 ) { $("#finalSearch").removeAttr('disabled'); }
});

But, I want the alert pop even if there's nothing in my field.

What I want to do:

  • There's nothing: error message.

  • There's one letter: no error message.

  • I remove this letter: error message.

  • If the field is populate but another function: no error message.

Thanks for help.

2
  • you can't detect field being filled by a function unless the other function triggers an event on the field and your handler code for the event then manages what you want Commented Dec 17, 2012 at 1:18
  • If 'keydown' event doesn't works for you, you must try 'keyup/keypress ' events with jquery events such as 'bind/delegate/on'. It should work on any one of these as i faced your issue several times before. Commented Dec 17, 2012 at 4:25

2 Answers 2

5

You should use the keyup event rather than keydown - on key down the field hasn't updated yet so testing the value at that point doesn't give you the right result.

It wouldn't hurt to do the same test on blur too, to allow for if the user changed the field via the Edit menu or drag'n'drop or whatever.

Also, unless using a really old version of jQuery use the .prop() method rather than .attr() to set the disabled state:

$('#location').on('keyup blur', function(event) {
   $("#finalSearch").prop('disabled', this.value.length === 0);
});
Sign up to request clarification or add additional context in comments.

Comments

1

you're pretty much already there, not sure where the issue is for you; but this works.

$('#location').on('keyup', function() {
    console.log($(this).val().length);
    if($(this).val().length == 0) {
        $('#finalSearch').prop('disabled', true);
    }else{
        $('#finalSearch').prop('disabled',false);
    }
});​

The jsFiddle

1 Comment

Solution was keyup. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.