Liftoff
Liftoff

Reputation: 25392

Prevent form submit from triggering buttons

I have a form with a few textboxes in it and a few buttons. I have a couple custom form elements that I am working on. One, in particular, is a textbox that will search a database onEnterClicked. This works just fine, but I also have a button that will run code onClick. Both of these appear to be linked to submitting the form.

<form onsubmit="return false;">
    <input type="text" id="autofill">
    ...
    <button id="upload">

When I run this jQuery code:

$("input#autofill").keyUp(function(e){
    //Do stuff
});

$("button#upload").click(function(){
    alert("test");
});

Pressing enter in the autofill textbox will show the test alert, but will not do any of the //do stuff code.

How can I prevent this from happening?

$(function(){
  
  $("#autofill").keyup(function(e){
    
    if(e.keyCode == 13)
    alert("Enter pressed");
    
    });
  
  $("#upload").click(function(){
    
    alert("Button clicked");
    
    });
  
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form onsubmit="return false;">
  <input type="text" id="autofill"/>
  <button id="upload">Click me to show an alert</button>
</form>

Upvotes: 1

Views: 159

Answers (2)

EternalHour
EternalHour

Reputation: 8621

In order to prevent the form from submitting with a <button>, you need to specify type="button".

<button id="upload" type="button">Click me to show an alert</button>

If you do not specify the type, the default is type="submit", which will submit the form when you press enter.

Upvotes: 5

wizzardz
wizzardz

Reputation: 5874

If you have strong reason for using the button type 'submit', then try this solution. Catch the 'keypress' event of the textbox and suppress it

$(function() {

  // handle the 'keypress' event to prevent the form submission
  $('#autofill').keypress(function(e) {

    if (e.keyCode == 13) {
      e.preventDefault();
      e.stopPropagation();
    }

  });

  $("#autofill").keyup(function(e) {

    if (e.keyCode == 13)
      alert("Enter pressed");

  });

  $("#upload").click(function() {

    alert("Button clicked");

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="f">
  <input type="text" id="autofill" />
  <button id="upload">Click me to show an alert</button>
</form>

Upvotes: 1

Related Questions