1

This is might be a little tricky.

I have a form with 10 text boxes(consider its name1, name2 .. name10)

what I want is when I focus on name1 text box and I hit "enter", the form should not submitted. instead I want to call a function.

but when I hit "enter" while focusing other form elements rather than name1, the form should get submitted.

Please suggest me if you think there are any other idea to do this.

NOTE: I cant move the element outside of the form.

Sandeep Sudhakaran
  • 1,072
  • 2
  • 9
  • 22

2 Answers2

2

use keypress event for the first input element and prevent the form from submitting by using event.preventDefault();

$(document).ready(function() {
  $("#name1").keydown(function(event){
    if(event.keyCode == 13) {
      calculate() // call your function here
      event.preventDefault();
    }
  });
  
  $( 'form' ).on( 'submit' , () => { // arrow function
    console.log("submited"); // form
} );
  function calculate() {
    console.log("prevent submitting");
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.js"></script>

<form>
  <input id="name1" type="text" />  
  <input type="text" />
  <input type="text" />
  <input type="text" />
  <input type="text" />
  <input type="text" />
  <input type="text" />
  <input type="text" />
  <input type="submit" value="Go">
</form>
Deepu Reghunath
  • 8,132
  • 2
  • 38
  • 47
  • why do you have `event.preventDefault();` and `return false;` together? do they not serve the same purpose? Also any specific reason for your 1st event handler is a normal function and your second event handler is an arrow function?? – Sudipto Roy Nov 02 '19 at 14:22
  • @SudiptoRoy here it is no use. If you would like to skip all code after the `event.preventDefault();` in the keydown method then you must use the return statement. – Deepu Reghunath Nov 02 '19 at 14:29
0
$('form').on('keypress', function(e) {
    if (e.code === 'Enter' && $(e.target).is('textarea')) {
        return false;
    }
});
Thanh Trung
  • 3,566
  • 3
  • 31
  • 42