0

I am doing client side validation to my registration page in html by using jquery. After submitted the form without giving text entries, I am getting the alert box with proper info what I have given in jquery function. But the problem is after click on "OK" button on alert box, the form is going to submit to action page directly. Can any one please help on it. Thanks, Swami.

<script>
function Submit(){
var fname = $("#fname").val();
if($("#fname").val() == "" ){
alert("please enter firsname")
return false;
};
};
</script>
<form method="post" action="#">
//fields here
<input type="button" value="Register" onclick="Submit();">
</form>
swamy
  • 29
  • 3
  • You need to put it on the onsubmit of the form. Not on the onclick of the button. – Ivar Oct 13 '17 at 13:16
  • 1
    Possible duplicate of [JavaScript code to stop form submission](https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission) – Ivar Oct 13 '17 at 13:28

1 Answers1

-1

Edit: Well, I rewrote my code snippet - it should work now.

<script>
function validateForm() {
  var fname = $("#fname").val();
  if(fname === "")
  {
    alert("Please enter your name!");
    return false;
  } else {
    $("#formid").submit();
    return true;
  }
}
</script>
<form id="formid" method="post" action="#">
  <input type="text" id="fname">
  <input type="button" value="Register" onclick="return validateForm();">
</form>

Have a look at this: JavaScript code to stop form submission.

Mr.Blob
  • 61
  • 5