Nik
Nik

Reputation: 31

prevent other event keydown on change

on my textbox i have 2 events onchange and keydown(for enter) now i did validation on onchange event if any validation fail then i raise alert but when i press press enter button if validation failed then i dont want to execute keydown event

any suggestion

Thanks, Nik

Upvotes: 3

Views: 2839

Answers (3)

UenX
UenX

Reputation: 162

Not sure what exactly you want but if you want to control an keydown event you can do like this:

<script type="text/javascript"> 

function onKeyDown() 

{  
   if(event.keyCode == 13 ) // if enter key  
   {  
// your validation-checking code here  
      if("validationfailed")  
      return false // prevent the event from happening if validation failed  
      else return true;// validating ok, allow it.  
   }  
   else  
   {  
      // another key, alow it.  
      return true;  
   }  
}  

</script>  
<input type="text" id="myText" onchange="validateText()" onkeydown="return onKeyDown()">  

Upvotes: 1

John
John

Reputation: 1540

You would want to create a global variable (boolean) that your onchange event will alter. Auto set that boolean to false, after it has been validated change it to true. After the keydown event is fired you will want to check and see if it was the enter key and that it passed all of your validation before taking any further action.

<script type="text/javascript">
     var passedChecks = false;

     function validateText(e) {
          var src = (window.event) ? window.event.srcElement: e;

          if (src.value == b) { // verify your logic is true.
               passedChecks = true;
          } 
     }

     function validateKey(e) {
          var src = (window.event) ? window.event.srcElement: e; 

          if (src.keyCode == 13) {
               if (passedChecks == true) {
                    // process your code.
               }
          }
     }
</script>

<input type="text" id="myText" onchange="validateText()" onkeydown="validateKey()">

Upvotes: 0

partoa
partoa

Reputation: 900

What you need to do is check the value of the key code on keydown for an invalid form. Also define a local variable, assuming that the 2 functions are defined in the same context, if they are not use apply to call them in the same context.

At that you can have a check if(event.keyCode != 13 && !invalid){ [Your operations] }

You can get more information about keycodes here.

I hope this helps.

Upvotes: 0

Related Questions