0

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
nitin
  • 571
  • 1
  • 4
  • 16

2 Answers2

2

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; }">
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    thanks for the reply.... I just had to add curly brackets and it worked – nitin Jun 28 '13 at 20:06
  • I just realized the same thing. The way I had it, all non-Return inputs would be ignored because `return false;` prevented the default action. – Barmar Jun 28 '13 at 20:08
0

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>
relic
  • 1,662
  • 1
  • 16
  • 24