Reputation: 3653
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 :
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
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();
}
});
Upvotes: 10
Reputation: 78520
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
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