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>";
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With