Wednesday, January 16, 2013

onkeypress and onkeydown, prevent enter key to submit a form in input



In JavaScript, the keypress event fires after the key is pressed and released, while keydown fires after the press but before the release.
Example:
     <script type="text/javascript">
      function handleKeyPress(e,form){
         var key=e.keyCode || e.which;
           if (key==13){
          e.preventDefault();      
       }
    }
        </script>
     <button  type='button' id="filter"  onclick="searchstudent()"> Serach </button>
    <input type="text"     id="search"  maxlength="80" onkeypress="handleKeyPress(event,this.form)" onkeyup="searchstudent()" >


In this example, when any key is pressed, Javascript function searchstudent() is called. We do not have to wait all the text  typed to start search. Somehow it is similar to Ajax.

 To prevent enter key or return key (key code 13) submit the form, we defined a user function handleKeyPress in onkeypress, which called e.preventDefault();   to prevent form submission.
 

No comments:

Post a Comment