onkeypress + onblur in javascript

隐身守侯 提交于 2019-12-25 08:08:43

问题


The onblur event in javascript is triggered when the element loses focus.

The onkeydown Occurs on an element that has the focus when a key is pressed down and occurs periodically until the key is released.

If I want to validate a date field, the onkeydown event concerns 9 and 13 (enter and tab key). But when I press the enter key, then I receive duplicate alert message. Of course in this case we have two tests, onblur and onkeydown event.

this is the html code :

<html:text      onblur="return onDateChange(this);"
        onkeydown="return onDateKeyPress(this);"/>

the onDateChange() method is :

function onDateChange(obj){
//validateField is an externatl javascript method which trigger an alert message if we have errors in date 
        if(validateField(obj,'date',dateFormat)){
        //do instructions
        }
}

and finally the onDateKeyPress() method is :

function onDateKeyPress(obj){
    if(window.event.keyCode == 9)
    {  
       if(validateField(obj,'date',dateFormat))
       {
           //do instructions
       }
    }
    if(window.event.keyCode == 13)
    {  
      if(validateField(obj,'date',dateFormat))
      { 
        //do instructions
      }
    }
}

So, the problem is to have one display alert message. Any suggestions?


回答1:


you can do it easily with jquery

$('#text_field_id').bind({
  blur: function(event) {
    if(validateField(this,'date',dateFormat)){
        //do instructions
        }
  },
  keydown: function(event) {
    if(event.keyCode == 9)
    {  
       if(validateField(this,'date',dateFormat))
       {
           //do instructions
       }
    }
    if(event.keyCode == 13)
    {  
       if(validateField(this,'date',dateFormat))
       {
           //do instructions
       }
    }

  }
});

you dont need to include onclick or onkeydown in your text element. One small question you want to execute same instructions in all cases or different instructions???? if you want to execute same instructions, lot of codes can be removed.




回答2:


In the solution above; keydownFired is true when blur is fired and the if branch of the code does nothing. so nothing happens.

If the blur has something to do other than showing alert; then the follwoing should work.

input.addEventListener('blur', function (e) { 

 doSomethingThatshldHappenAlwaysOnBLur();

    if (keydownFired) { 

      keydownFired = false 

    } else { 
        showAlert();    
  } 
}) 


来源:https://stackoverflow.com/questions/8446788/onkeypress-onblur-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!