HTML5 form validation for submit AJAX button

I have the following view. I like the new HTML5 form validation, and I'd rather keep it. But. I don’t like it when the button is clicked it refreshes the page (submit form).

Instead, I would rather use a button to invoke some AJAX to refresh page elements without refreshing the entire page. However, when I set type="button" , what happens is that HTML5 form validation stops running when the button is clicked.

How can I use HTML5 form validation without triggering page refresh / submit distribution?

Note that I am not interested in the AJAX elements of this problem, just the HTML5 validation issue.

 echo "<form>"; echo "<td><input id=\"link_add_title\" type=\"text\" class=\"form-control\" placeholder=\"URL Title\"></td>"; echo "<td><input id=\"link_add_url\" type=\"url\" class=\"form-control\" placeholder=\"Your URL\"></td>"; echo "<td><input id=\"link_add_budget\" type=\"number\" step=\"any\" class=\"form-control\" placeholder=\"Budget\"></td>"; echo "<td><button class=\"btn btn-sm btn-success\"><i class=\"fa fa-check\"></i> Add</button></td>"; echo "</form>"; 
+5
jquery html5 forms
source share
2 answers

This way you prevent the actual submission, but HTML5 validation triggers:

 $('form').submit(function(event){ event.preventDefault(); }); 

As Samveen points out , this method should be preferable to listening to the onclick event of the <button> / <input type="submit"> element, since the latter will prevent HTML5 validation in addition to the normal submit form - see the script .

+12
source share

Try the submit button.

 html <input type="submit" class="your-button-class" /> js $(document).on('click','.your-button-class',function(){ //your code return false; //this will prevent the page refresh }); 
0
source share

All Articles