简体   繁体   中英

onkeypress + onblur in Javascript

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?

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.

Recently I had a problem with having onkeypress and onblur attached to one element. One of the major problems with onkeypress and onkeyblur is that they by nature will trigger each other :) (Triggered? Get it? That's a joke btw. I am bad at jokes, sorry!)

The solution is simple and stupid. Instead of having an alert when onkeypress happens AND when onblur happens you trigger only onblur . How?

//I gave this thing and id. You should always give your things and id. Ids are cool and I love them.
<html:text id="thisIsMyId"
  onblur="return onDateChange(this);"
  onkeydown="return onDateKeyPress(this)";
/>

the onDateChange() method will stay pretty much the same:

//This will stay the same, you will see why, soon
function onDateChange(obj){
//ValidateField is an externatl javascript method which trigger an alert message if we have errors in date 
//If you might have noticed tha **this validate** function is used 3 times, why?
    if(validateField(obj,'date',dateFormat)){
      //do instructions and **I assume the alert?**
    }
}

Now, we will make onDateKeyPress() a little bit blurry :)

//Here is where we strike
function onDateKeyPress(obj){
    //This looks weird but it checks if the keycode actually works in the browswer
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    //Instead of having 2 ifs just make one if with and the logical operator "or" :)
    if(keycode == 13 || keycode == 9){
      //I am not sure if oyu need to use this but in the example I had, I had to use 
      //my validation-function otherwise it would just submit
      if(validateField(this,'date',dateFormat)){
        //If you have a submit form or something this can help
        event.stopPropagation();

        //we just trigged the onBlur Handler by "blurring" this thing :)
        document.getElementById('thisIsMyId').blur();
      }
}

With this we did cut one validation and have to write the logic only once. Only in the onDateChange() function.

If someone can make it even better please comment below. I would like to make the code even shorter.

At the end of the day it still depends on the specific situation. It worked for me but this is not a "fits-all-solution".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM