I’m trying to call a simple function onsubmit. I tried using onsubmit and also a listener with jQuery. My problem is that when the user presses enter he gets redirected to mysite.com?
<form id="teleport">
<input id="tInput" type="text" value="Type a location" />
<input type="button" id="tSubmit" value="Submit"/>
</form>
$("#teleport").submit(function () {
teleport(document.getElementById('tInput').value);
});
How do I prevent anything from happening when submitting? Also .submit() is only detecting the enter key, how do I listen for both enter key and clicks on the submit button?
You need to prevent the default action of the form. You can do that with
event.preventDefault():Alternatively, you could
return falseinside thesubmitevent handler for the same effect.The easiest way to make the button submit the form too will be to change it’s type to
submit:<input type="submit" id="tSubmit" value="Submit" />Or you could attach a
clickevent handler to your current button and trigger thesubmitevent of the form.