JS keypress events

0 votes
369 views
added Feb 14, 2018 in Javascript by LC Marshal Captain (25,790 points)
edited Jul 13, 2018 by LC Marshal
HTML type attributes only allows numeric input

<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:

$( "#target" ).keypress(function() {
  console.log( "Handler for .keypress() called." );
});
0 votes
responded Apr 3, 2018 by LC Marshal Captain (25,790 points)
edited Jul 13, 2018 by LC Marshal
<!--Javascript - How to assign an onkeypress event to an input element.-->

<input type="text" id="demo" onkeypress="myFunction()">

<script>
function myFunction() {
    document.getElementById("demo").style.backgroundColor = "red";
}
</script>

 

0 votes
responded Apr 3, 2018 by LC Marshal Captain (25,790 points)
edited Jul 13, 2018 by LC Marshal
<!--Uses the addEventListener() method to attach a keypress event to an input element.-->

<input type="text" id="demo">

<script>
document.getElementById("demo").addEventListener("keypress", myFunction);

function myFunction() {
    document.getElementById("demo").style.backgroundColor = "red";
}
</script>
lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...