开发者

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 re开发者_如何学编程directed 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():

$("#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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜