开发者

jQuery cancel event on keypress escape

开发者 https://www.devze.com 2023-03-29 21:32 出处:网络
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.

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 c开发者_StackOverflowlick 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();
      }    
    });  
  });                                        
});


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


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");
});   


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

0

精彩评论

暂无评论...
验证码 换一张
取 消