lisovaccaro
lisovaccaro

Reputation: 33956

Simple function onSubmit?

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?

Upvotes: 0

Views: 475

Answers (2)

klob
klob

Reputation: 687

Prevent submiting a form:

$("#teleport").submit(function (e) {
   teleport(document.getElementById('tInput').value);
   e.preventDefault();
});

Submit event catches any way of submitting a form - both with clicking the submit button and enter key press.

Upvotes: 2

James Allardice
James Allardice

Reputation: 165961

You need to prevent the default action of the form. You can do that with event.preventDefault():

$("#teleport").submit(function (e) {
    e.preventDefault();
    teleport(document.getElementById('tInput').value);
});

Alternatively, you could return false inside the submit event 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 click event handler to your current button and trigger the submit event of the form.

Upvotes: 2

Related Questions