EN
JavaScript - onkeypress event example
0 points
In this article, we would like to show you onkeypress
event example in JavaScript.
Quick solution:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.addEventListener('keypress', function() {
4
console.log('onkeypress event occurred.');
5
});
or:
xxxxxxxxxx
1
<input type="text" onkeypress="handleKeypress()">
or:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.onkeypress = function() {
4
console.log('onkeypress event occurred.');
5
};
There are three common ways how to use onkeypress
event:
- with event listener,
- with element attribute,
- with element property.
In this section, we want to show how to use onkeypress
event on input
element via event listener mechanism.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Type something: </p>
5
<input type="text" id="my-input">
6
<script>
7
var myInput = document.querySelector('#my-input');
8
9
myInput.addEventListener('keypress', function() {
10
console.log('onkeypress event occurred.');
11
});
12
</script>
13
</body>
14
</html>
In this section, we want to show how to use onkeypress
event on input
element via attribute.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Type something: </p>
5
<input type="text" onkeypress="handleKeypress()">
6
<script>
7
function handleKeypress(){
8
console.log('onkeypress event occurred.');
9
}
10
</script>
11
</body>
12
</html>
In this section, we want to show how to use onkeypress
event on input
element via property.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Type something: </p>
5
<input type="text" id="my-input">
6
<script>
7
var myInput = document.querySelector('#my-input');
8
9
myInput.onkeypress = function() {
10
console.log('onkeypress event occurred.');
11
};
12
</script>
13
</body>
14
</html>