-1

I've got a problem regarding my contact form page. I did callback after clicking the submit button. I tried not to fill name textbox but form still submits.


My code:

function sendFeedback() {
  alert("Thank you for the feedback :)");
}
<form>
  <p class="font3">Name:</p>
  <input name="name" type="text" maxlength="50" size="30" required/>
  <br />

  <p class="font3">Email:</p>
  <input name="email" type="email" placeholder="" required/>
  <br />

  <p class="font3">Subject:</p>
  <input name="subject" type="text" required/>
  <br />

  <p class="font3">Message:</p>
  <textarea name="comment" row="80" cols="30" required></textarea>
  <br>
  <br>

  <input type="submit" value="Submit" onclick="sendFeedback()">
  <input type="reset" value="Reset">

</form>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
mosyahri2
  • 7
  • 3
  • you can use event.preventDefault() to stop the default behaviour of the form. Have you tried that? – dvenkatsagar Jan 31 '16 at 05:51
  • Check this answer: http://stackoverflow.com/questions/34884011/sending-json-to-php-server-using-jquery-ajax-json-error/34889060#34889060 I'm doing validations and error handling here. – devtye Jan 31 '16 at 05:54
  • 1
    `alert` won't prevent submit. Suggest you study some form validation tutorials. – charlietfl Jan 31 '16 at 05:58
  • I thinks a possible duplicate of this : http://stackoverflow.com/questions/3350247/how-to-prevent-form-from-being-submitted – dvenkatsagar Jan 31 '16 at 06:02
  • Refer following post: http://stackoverflow.com/questions/17646471/stopping-form-submit-if-the-validation-fails – Rajesh Jan 31 '16 at 06:05

2 Answers2

0

You should change <form> to <form onsubmit="test()",where test() would go something like this:

test(e){
  e.preventDefault();
  /* do some validations here */
  document.querySelector("form").submit();
}

Hope it helps

dvenkatsagar
  • 936
  • 7
  • 22
0

The form submitting and your alert triggering are two completely different things. The required attributes you have on the inputs are working correctly. If you leave any of the required inputs blank, the form will not submit to the server, instead you'll trigger standard error messaging in whatever browser you're using (usually a red outline and a popover).

The bit of JavaScript you have (i.e. your alert) will trigger regardless of whether the form submits successfully or not since it's executed BEFORE the submit goes through. You need to either do something like e.preventDefault() or return false at the end of your function, but that will prevent the form from being submitted altogether.

As @dvenkatsagar said, your best option is to change your onclick to onsubmit.

michael
  • 748
  • 4
  • 10