Reputation: 591
I have two textbox and two buttons on a webpage.
Each textbox has its own keypress function which checks for the return key and calls a particular javascript function.
But the problem is if I start typing on any text box and hit return both the functions are being called.This is happening only in Internet Explorer.
Onkeypress is being called as an attribute of input tag
onkeypress="if(event.keyCode==13) submitEmail();"
and
onkeypress="if(event.keyCode==13) login();"
Thanks
Upvotes: 0
Views: 1728
Reputation: 782148
This is because of event bubbling. When an event happens on an element, it also happens on all the elements that contain it, in sequence walking up the DOM tree. So pressing Return on the input box also presses return on the window.
If you add return false;
to the onkeypress
attribute of the input
element, that will prevent bubbling.
<input ... onkeypress="if(event.keyCode==13) { submitEmail();return false; }">
Upvotes: 2
Reputation: 1704
You could try setting them in your script tag or external js file, targeting each input before setting the keypress function.
<input type="text" id="email">
<input type="text" id="login">
<script>
var emailBox = document.getElementById("email")
emailBox.onkeypress = function(e){
if(e.keyCode == 13) submitEmail();
}
var loginBox = document.getElementById("login")
loginBox.onkeypress = function(e){
if(e.keyCode == 13) login();
}
</script>
Upvotes: 0