JS keypress events

0 votes
571 views
added Feb 14, 2018 in Javascript by LC Marshal Captain (25,790 points)
edited Jul 13, 2018 by LC Marshal
  1. HTML type attributes only allows numeric input
  2.  
  3. <input id="contact" name="" type="tel" maxlength="12" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>

 

3 Responses

0 votes
responded Apr 3, 2018 by LC Marshal Captain (25,790 points)
edited Jul 13, 2018 by LC Marshal

The event handler can be bound to the input field:

  1. $( "#target" ).keypress(function() {
  2. console.log( "Handler for .keypress() called." );
  3. });
0 votes
responded Apr 3, 2018 by LC Marshal Captain (25,790 points)
edited Jul 13, 2018 by LC Marshal
  1. <!--Javascript - How to assign an onkeypress event to an input element.-->
  2.  
  3. <input type="text" id="demo" onkeypress="myFunction()">
  4.  
  5. <script>
  6. function myFunction() {
  7. document.getElementById("demo").style.backgroundColor = "red";
  8. }
  9. </script>

 

0 votes
responded Apr 3, 2018 by LC Marshal Captain (25,790 points)
edited Jul 13, 2018 by LC Marshal
  1. <!--Uses the addEventListener() method to attach a keypress event to an input element.-->
  2.  
  3. <input type="text" id="demo">
  4.  
  5. <script>
  6. document.getElementById("demo").addEventListener("keypress", myFunction);
  7.  
  8. function myFunction() {
  9. document.getElementById("demo").style.backgroundColor = "red";
  10. }
  11. </script>
lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...