Jquery: Prevent reloading page when pressing input type=submit
I have the following code in a MVC 3 (Razor) project:
<div class=开发者_如何学C"user_info" id="id_user_info">
<script type="text/ecmascript" >
$(function () {
$('#buttonClear').live('submit', function (e) { return false; });
$('#buttonClear').bind('click', function () {
$('username').value = "";
$('password').value = "";
});
</script>
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "loginForm" }))
{
<label for="username">Enter:</label>
<input name="username" id="username" type="text" value="" /><br />
<input name="password" id="password" type="password" value="" /><br />
<input name="rememberMe" id="rememberMe" type="checkbox" value="true" />
<label for="rememberMe">Remember me?</label><br />
<input id="buttonLogin" type='submit' value="Login" />
<input id="buttonClear" type='submit' value="Clear" />
}
</div>
I need to keep the "buttonClear as type sumbit because of the style, but i need to disable/avoid/prevent it from reloading the page once pressed.
Is there a way to remove the "submit event" from "buttonClear"?
Thanks Ricardo
$('#buttonClear').click(function(e){
// do whatever actions you need here
e.preventDefault();
});
I would suggest removing the handler you're binding to the submit
event, and instead using preventDefault
in the click
event handler:
$('#buttonClear').bind('click', function (e) {
e.preventDefault();
$('username').value = "";
$('password').value = "";
});
The submit
event approach you have tried will not work because submit
events can only be bound to form
elements, not the buttons that submit the form.
try e.preventDefault();
$('#buttonClear').bind('click', function (e) {
e.preventDefault();
$('username').value = "";
$('password').value = "";
});
While I realize this post is a little older, I wanted to provide this answer for the record as well.
<input id="buttonClear" type='submit' value="Clear" />
Normally you would not have multiple submit buttons for one form. Additionally, since you don't actually want submit functionality it wouldn't be accurate to use this type. Finally you are looking for a "Clear" or "Reset" functionality. Your button should be:
<input id="buttonClear" type="reset" value="Clear" />
Why not just
$('#buttonClear').click(function() {
return false;
});
精彩评论