AJAX按钮提交的HTML5表单验证

AJAX按钮提交的HTML5表单验证

问题描述:

我有以下表格。我喜欢新的HTML5表单验证,我宁愿保留它。然而。我不喜欢按下按钮时刷新页面的方式(表单提交)。

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).

相反,我更喜欢使用按钮触发一些AJAX来刷新页面元素而不刷新整个页面。但是,当我设置 type =button时,按下按钮时HTML5表单验证将停止触发。

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.

如何使用HTML5表单验证,同时不会触发刷新/提交页面的传播?

请注意,我是我不关心这个问题的AJAX元素,只关注HTML5验证问题。

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>";


这样可以防止实际提交,但HTML5验证会触发:

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

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

  event.preventDefault();

});

Samveen 指出,这种方式应该优先于听取< button> onclick 事件> / < input type =submit> 元素,因为后者除了正常表单提交外还会阻止HTML5验证 - 看小提琴

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.