0

Good day,

Can anyone please help me how can I stop my form from submitting whenever I press "enter" on a certain input box inside a form.

I have a table where use can dynamically add/remove row. And I have also an input box where user types/input number of rows he/she want to add. What I want to do is, the user can press enter instead of clicking the add row button when hes on the add row input box without actually submitting the form.

here is my js:

$("#toBeAdded").bind("keyup",function(e){
  var code = e.keyCode || e.which;
   if(code == 13) { //Enter keycode
     console.log("enter");
      return false;
     e.preventDefault();
    }

});

my html

<form>
 <div>
 <input name='amout'></amount><input name='qty'></amount>..etc
 </div>

 <input type="text" id="toBeAdded" class="form-control">
  <div class="input-group-btn ">
    <button type="button" id="btnAddRow" class="btn btn-primary ">Add Row</button>
  </div>
 </form>

the above code doesnt work, it does display log message but then it will submit the form after. any thoughts please

melvnberd
  • 3,093
  • 6
  • 32
  • 69
  • 2
    well the `e.preventDefault();` line will never be run because of the `return`. – epascarello Feb 18 '14 at 15:13
  • Exactly. Put it like this: e.preventDefault(); return false; – spassvogel Feb 18 '14 at 15:13
  • still wont work :/ I even tried `$("form").submit(false);` xD but still wont work! – melvnberd Feb 18 '14 at 15:16
  • `return false` in jQuery event handlers effectively do `e.preventDefault()` and `e.stopPropagation()`, so it's unnecessary to have it with `e.preventDefault()`. You can read more here: http://stackoverflow.com/questions/5927689/when-should-i-use-return-false-in-jquery-function . Also, `var code = e.keyCode || e.which;` should be unnecessary - jQuery normalizes the keycode into `e.which`, so just use `e.which` – Ian Feb 18 '14 at 15:22

3 Answers3

3

Change the keyup event to keydown

$("#toBeAdded").on("keydown",function(e){

You can not cancel the action after it has happened.

epascarello
  • 204,599
  • 20
  • 195
  • 236
1

You are returning from callback before calling preventDefault(). Switch the order and it should work.

$("#toBeAdded").bind("keyup",function(e){
  var code = e.keyCode || e.which;
  if(code == 13) { //Enter keycode
      console.log("enter");
      e.preventDefault();
      return false;
  }
});
Mika Tuupola
  • 19,877
  • 5
  • 42
  • 49
0

Try this, use the keypress event it runs before submit so you can abort:

$('form').find('input').keypress(function(e){
    if ( e.which == 13 ) // Enter key = keycode 13
    {
        return false;
    }
});
Wilmer
  • 448
  • 2
  • 4