AJAX按钮提交的HTML5表单验证

时间:2022-11-24 09:46:11

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

我有以下表格。我喜欢新的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.

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

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

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

Note that I'm not concerned with the AJAX elements of this problem, just the HTML5 validation issue.

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

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

2 个解决方案

#1


12  

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

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

$('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.

正如Samveen所指出的,这种方式应该比听

#2


0  

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
});

#1


12  

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

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

$('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.

正如Samveen所指出的,这种方式应该比听

#2


0  

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
});