Prevent both blur and keyup events to fire after pressing enter in a textbox

后端 未结 8 421
粉色の甜心
粉色の甜心 2021-01-11 10:13

After pressing enter I would like that only the keyup event be fired but blur is fired first. How to cancel blur when

相关标签:
8条回答
  • 2021-01-11 11:19

    I have an input where a user can change it, focus out or press enter. But when you press enter both keydown and blur is triggered, so myFunction() gets triggered twice.

    So instead of writing two separate functions for keydown and blur, you can instead put them into a single function:

    my_input.on('keydown blur', function (e) {
    
        // was it the Enter key?
        if (e.which == 13) {
            $(this).blur();
        }
    
        if (e.type == 'blur') {
            myFunction();
        }
    
    });
    
    0 讨论(0)
  • 2021-01-11 11:21

    I Couldn't alter class attribute so i'd ended up with,

    $(".textbox").on("blur",function () { 
        if($(this).attr('flag')!='1') 
            alert("blur Event fired");
    });
    
    $(".textbox").on("keyup",function (event) { 
        $(this).attr('flag','1');
        if(event.keyCode == 13){ // Detect Enter
            alert("KeyUp fired after pressing Enter");
        }
        $(this).attr('flag','0');
    });
    
    0 讨论(0)
提交回复
热议问题