Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 form validation for AJAX button submit

Tags:

html

jquery

forms

I have the following form. I like the new HTML5 form validation and I would prefer to keep it. However. I don't like the way that when the button is pressed it refreshes the page (form submit).

Instead I would prefer to use the button to trigger some AJAX to refresh page elements without refreshing the entire page. However, when I set type="button" what happens is that the HTML5 form validation ceases to trigger when the button is pressed.

How can I use HTML5 form validation, while not triggering propagation of refreshing/submitting the page?

Note that I'm not concerned with 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>";
like image 813
Amy Neville Avatar asked Nov 16 '13 16:11

Amy Neville


2 Answers

This way you prevent actual submit, but HTML5 validation triggers:

$('form').submit(function(event){

  event.preventDefault();

});

As Samveen points out, this way should be preferred over listening to the onclick event of the <button>/<input type="submit"> element, because the latter would prevent HTML5 validation in addition to normal form submit - see fiddle.

like image 58
moonwave99 Avatar answered Oct 20 '22 03:10

moonwave99


With a submit button try..

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
});
like image 23
Achilles Avatar answered Oct 20 '22 05:10

Achilles