1

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>

2
  • It's hard to understand what you are trying to accomplish. Commented Nov 5, 2014 at 4:04
  • @EternalHour I want //do stuff to run when I press enter in the text box; right now it is showing the alert("test"), when it should not be, as I show in the snippet. Try pressing enter in the text box. It will show "Button Clicked" instead of "Enter pressed" Commented Nov 5, 2014 at 4:05

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.