0

I need to write an event handler when user clears the text field and moves out of focus from the same.

I'm using the following function to catch "focus out" event.

$("input[type=text]").blur(function () {
}

I have the followingfunction to capture clear field event.

$("input[type=text]").keyup(function() {
            if (!this.value) {
     }
}

I tried using the keyup() function inside blur() since I need to capture the focus out and then clear field. This is how my code looks like:

$("input[type=text]").blur(function () {
$(this).keyup(function() {
            if (!this.value) {
            }
      }
}

But it doesn't work. Clear field event is triggered even before focus is out of the field. Also, it is triggering the event multiple times. What is the problem here?

2 Answers 2

3

I think that is more simple:

$('input').on('blur', function(e) {
    if(!$(this).val()) {
         // IS NO VALUE IN THE INPUT
         $(this).trigger('blur'); // trigger the blur event
    }
});
5
  • I understand better your problem. Try this: $('input').on('keyup', function(e) { if(!$(this).val()) { $(this).trigger('blur'); }); Jul 6, 2015 at 10:21
  • So this will also trigger when the user just leaves the textbox which has already been empty. (No clearing actually).
    – TaoPR
    Jul 6, 2015 at 10:23
  • If the user leaves the input with keyboard: yes, but is a workaround detecting TAB key to avoid it. Jul 6, 2015 at 10:25
  • 1
    Detecting value changes might be another viable workaround. The user may leave with a mouseclick on other element rather than a TAB key too. However, your answer is a solution I would have taken.
    – TaoPR
    Jul 6, 2015 at 10:33
  • You are correct, @Tao . If he changes "keyup" by "change" in on() function is better solution. But is a problem, because "change" event fires when user blur of the input, this solution is not valid too Jul 6, 2015 at 10:37
0

Here you are:

$("input[type=text]").on('blur', function() {
  alert('blur');
});
$("input[type=text]").on('input', function() {
  if (!$(this).val()) {
    alert("input nothing");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

Hope this helps.

1
  • How you produce it? :|
    – hungndv
    Jul 6, 2015 at 10:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.