user2304394
user2304394

Reputation: 323

Stop form submission and keep form values

I have added a validation check on my form submission but problem is that it stopped the form from being submitted but it also reset my whole form. Kindly let me know how can i on return false also stop the form submission and stop resetting the whole form. Thanks

function error()
{
   if (!$("#form1 input[name='radio']:checked").val()) {
     alert('Error: Please select any check box!');
     return false;
   }
   else {
     //alert('One of the radio buttons is checked!');
   }
}

<form name="form1" id="form1">
  <input name="Name" type="text" id="name" size="70" />
  <input name="Age" type="text" id="age" size="70" />
  <input type="radio" name="radio" id="A18" value="18" />
  <input type="radio" name="radio" id="A19" value="19" />
  <input type="submit" onclick="error();" />
</form>

Upvotes: 2

Views: 435

Answers (2)

user229044
user229044

Reputation: 239290

You need to handle the form's submit event with your validation function, and return false:

$("#form1").submit(error);

Returning false from your submit handler will cancel the form submission, and the current state of the form's elements will be maintained.

Upvotes: 2

Pointy
Pointy

Reputation: 413720

You need to do more than just return false from the function:

<input type="submit" onclick="return error();" />

Because the value of the "onclick" attribute is essentially used as the body of the actual handler function, it needs its own return statement.

edit — meagar's answer is a good idea - it would be wise to handle the "submit" event on the form instead of the "click" event on the button. If you set up the event handler via jQuery as in his example, the return in the "error" function is all you need.

Upvotes: 2

Related Questions