html表单-onclick不会触发`required`属性 [英] html form - `required` attribute not triggered with onclick confirm

查看:629
本文介绍了html表单-onclick不会触发`required`属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html表单,其中的输入字段在提交前需要一个值,要实现此目的,我使用的是html5中的required属性,该属性在下面的代码段中显示,标题为 Form One

I have a html form with input fields that require a value before submission and to achieve this I am using the required attribute in html5 Which is shown in the snippet below with the header Form One.

问题是我想在单击删除按钮后添加确认弹出消息-询问用户是否要继续.

The problem is I'd like to add a confirm pop-up message after the delete button is clicked -- asking if the user wants to continue.

我已经在下面显示的标题为 Form Two 的代码段中完成了此操作,但是问题是,当输入字段为空并提交时,必填属性未显示.

I have done this in the snippet shown below with the header Form Two but the problem is, the required attribute is not showing when the input field is empty and submitted.

在触发所需方法之前先提交表单.任何人都有解决html5功能不足的想法吗?

The form gets submitted before the required method is triggered. Anyone has any ideas to solve this html5 incompetence?

谢谢

<h2>Form One </h2>

<form method="post" action="example.com" id="delete_page">

  Name : <input type="name" required><br>
  <input type="button" value="Cancel">
  <input type="submit" value="Delete">

</form>
<hr>
<h2>Form Two </h2>
<form method="post" action="example.com" id="delete_page">

  Name : <input type="name" required><br>
  <input type="button" value="Cancel">
  <input type="submit" onclick="confirm('Are you sure you want to submit')" value="Delete">

</form>

推荐答案

尝试在<form>而不是按钮上使用onsubmit.

Try using onsubmit on your <form> rather than the button.

<h2>Form Two </h2>
<form method="post" action="example.com" id="delete_page"
      onsubmit="return confirm('Are you sure you want to submit?')">

  Name : <input type="name" required><br>
  <input type="button" value="Cancel">
  <input type="submit" value="Delete">

</form>

浏览器表单验证仅在 submit 事件中启动.

Browser form validation only kicks in on a submit event.

如果用户选择取消" 弹出窗口,这还将阻止您的表单提交.

This will also prevent your form from submitting if the user chooses to "Cancel" the popup.

这篇关于html表单-onclick不会触发`required`属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆