Yannick
Yannick

Reputation: 3653

jQuery cancel event on keypress escape

From the example in my Fiddle you will see that I'm trying to once the user click on the button escape it will show the div status as cancel.

What I did was :

  1. enter some value in the input box
  2. just click on tab to run blur event (status is changed to saved)
  3. change the value and then click on escape (the input is remove BUT the status is back to saved and not cancel)

I know it runs the code under the if statement for the escape event but after that it still goes to the blur event and change the status to saved.

See my Fiddle

HTML:

<input id="input"/>
<div id="status">status</div>

jQuery:

$(document).ready(function() {
  $('#input').live('blur', function(e){
    $('#status').html("saved");
    $('#input').live('keyup', function(e){
      if (e.keyCode == 27) { 
        $('#status').html("cancel");
        $('#input').remove();
      }    
    });  
  });                                        
});

Upvotes: 1

Views: 6014

Answers (3)

Shef
Shef

Reputation: 45589

If you do the following it does not!

$('#input')
    .on('blur', function(e){
        $('#status').html("saved");  
    })
    .on('keyup', function(e){
        if (e.which == 27) { 
            $('#status').html("cancel");
            $('#input')
                .off('blur') // unbind the blur event
                .remove();
        }    
    });     

Here is a forked demo

Upvotes: 10

Joseph Marikle
Joseph Marikle

Reputation: 78520

Demo

It's the onblur event that's causing your problem. When the textbox is removed, it triggers the onblur which sets the label to "saved". You can amend this by adding a "canceled" class to the textbox and only save if not canceled

$('#input').live('keyup', function(e){
    if (e.keyCode == 27) { 
        $('#status').html("cancel").addClass("canceled");
        $('#input').remove();
    }    
});  
    
$('#input').live('blur', function(e){
        $('#status:not(.canceled)').html("saved");
});   

Upvotes: 1

Leslie Hanks
Leslie Hanks

Reputation: 2377

The blur event fires when an input loses focus. You will need to use the keypress event to pick up the ESC key event.

Upvotes: 0

Related Questions