Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button Click event fires when pressing Enter key in different input (no forms)

This logic is firing when pressing "Enter" in the "Amount" input, and I don't believe it should (it doesn't in Chrome). How can I prevent this, and if not prevent it in IE, handle it so that the logic in the click event does not fire.

<html>
 <body>
   <div id="page">
     <div id="financed_amount">
      <h1>Financed Amount:</h1>
      <input type="text" id="amount" value="" />
     </div>
     <h1>Finance Options</h1>
     <div>
      <a id="shareLink" rel="leanModal" name="email" href="#email"></a>
      <button id="btnShare" class="share">Share this report</button>
     </div>
    </div>
   </body>
</html>

Script

$("#btnShare").click(function (e) {
    // This logic is firing when pressing "Enter" in the "Amount" input
});
  • Jquery: 1.7.2
  • IE 9
  • (Works in Chrome)
like image 861
contactmatt Avatar asked Oct 15 '22 11:10

contactmatt


People also ask

Does enter key trigger click event?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.

How do you submit a form when Enter key is pressed?

To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. Explanation: We use the jQuery event. which to check the keycode on the keypress.

Which of the following event is triggered whenever the user presses Enter key while editing any input field in the form?

The keyup event occurs when a keyboard key is released.


2 Answers

I had the same problem and solved it by adding type="button" attribute to the <button> element, by which IE thinks the button as a simple button instead of a submit button (which is default behavior of a <button> element).

like image 145
pallati Avatar answered Nov 08 '22 14:11

pallati


I ran into this problem today. IE assumes that if you press the enter key in any of the text fields, you want to submit the form -- even if the fields are not part of a form and even if the button is not of type "submit".

You must override IE's default behavior with preventDefault(). In your jQuery selector, put in the div that contains the text boxes you want to ignore the enter key -- in your case, the "page" div. Instead of selecting the whole div, you could also specify the text boxes you want to ignore specifically.

$('#page').keypress(function(e) {
    if(e.which == 13) { // Checks for the enter key
        e.preventDefault(); // Stops IE from triggering the button to be clicked
    }
});
like image 27
Christian Clinton Avatar answered Nov 08 '22 15:11

Christian Clinton