Reputation: 457
I have a form that currently doesn't refresh the page if I click the button that submits it. But if I press Enter when a text input is focused, it will refresh the page. Is there any way to make it so pressing enter on the text input acts the same as the button so the page doesn't refresh?
function redeemTokens() {
var code = $("#code").val();
$.post("_post_redeemtokens.php", { code: code },
function(data) {
$('#resultRedeemTokens').fadeIn('slow').html(data);
});
}
<form method="post">
<input id="code" name="code" type="text" placeholder="Code">
<input type="button" onclick="redeemTokens();" value="Redeem" />
</form>
Thank you for your help in advanced!
Upvotes: 2
Views: 6034
Reputation: 331
How about this? Pressing [enter] in a text field will be like clicking the [tab] key.
/* prevent Enter as Submit (on textboxes) and, instead, tab to the next field */
$("input").keypress(function(event) {
"use strict";
if (event.keyCode == 13)
{
event.preventDefault();
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
if (idx == inputs.length - 1)
{
inputs[0].select()
}
else
{
inputs[idx + 1].focus();
inputs[idx + 1].select();
}
return false;
}
});
Upvotes: 2
Reputation: 6878
$("form").submit(function(e) {
e.preventDefault();
redeemTokens();
});
Upvotes: 1
Reputation: 44834
try something like
$('body').keyup(function (event) {
if (event.keyCode == '13') {
$("form").submit ();
// or call redeemTokens directly
}
return false;
});
Upvotes: 0
Reputation: 388316
Use a submit handler for the form and, return false from it to prevent the default submit
This method saves the data on form submit - ie click on the submit button for enter key press
<form method="post" onsubmit="redeemTokens(); return false">
<input id="code" name="code" type="text" placeholder="Code">
<input type="submit" value="Redeem" />
</form>
or this saves only on click on the button but form submit is prevented on enter key
<form method="post" onsubmit="return false">
<input id="code" name="code" type="text" placeholder="Code">
<input type="button" onclick="redeemTokens();" value="Redeem" />
</form>
Note: Since You are using jQuery it is advisable to use jQuery event handlers instead of inline event handlers
Upvotes: 3