Reputation: 552
I have this simple document:
<!DOCTYPE html>
<html>
<body>
<input id="mytext" onkeypress="myfun(e)"></input>
<p id="demo"></p>
<script> function myfun(e){
if(e.keyCode==13) alert('Enter Key Pressed');}
});
</script>
</body>
</html>
what I want is:
when user press enter key on mytext, show an alert to inform the user like this message : Enter Key Pressed
I did every thing like above, But it doesn't work and no any alert is shown when enter pressed on mytext.
Help Please!..
Upvotes: 0
Views: 2410
Reputation: 57944
You can add an event listener to listen for the onkeypress
event:
document.getElementById('mytext').addEventListener('keypress', function(e) {
if(e.keyCode == 13) alert('Enter Key Pressed');
});
Also, input tag's don't have a closing tag. Here's a live example
If you want to call it inline as a handler, try this:
<input id="mytext" onkeypress="myfun(event)">
<p id="demo"></p>
<script>
function myfun(event){
var key = event.keyCode || event.which;
if(key === 13) alert('Enter Key Pressed');
}
</script>
You must use event
as a parameter to make sure it works correctly as a handler. Now, get's the key code and check if it's 13, then alerts.
Upvotes: 2
Reputation: 1074
Your code works when you replace myfun(e) with myfun(event). I also corrected some syntactical errors.
<html>
<body>
<input id="mytext" onkeypress="myfun(event)"></input>
<p id="demo"></p>
<script>
function myfun(e){
if(e.keyCode==13) alert('Enter Key Pressed');
};
</script>
</body>
</html>
Upvotes: 0