Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Prevent reloading page when pressing input type=submit

I have the following code in a MVC 3 (Razor) project:

<div class="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

like image 210
Ricardo Avatar asked Dec 09 '22 07:12

Ricardo


2 Answers

$('#buttonClear').click(function(e){
  // do whatever actions you need here
  e.preventDefault();
});
like image 169
kinakuta Avatar answered Feb 18 '23 08:02

kinakuta


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.

like image 32
James Allardice Avatar answered Feb 18 '23 09:02

James Allardice