繁体   English   中英

使用 CSS 使任一 HTML 输入字段成为必需

[英]Make either one HTML input field required using CSS

是否可以根据需要制作loginidemail ,只需使用 CSS 或 HTML(而不是使用 Javascript)?

<html>

<body>
  <form>
    <!-- Atleast one field should be filled by user -->
    <label>loginid</label>
    <input required>

    <label>email</label>
    <input required>
  </form>
</body>

</html>

抱歉,不可能仅使用 CSS 和 HTML 来使“loginid”或“email”这两个字段中的一个成为必填字段。

这种类型的功能需要使用 JavaScript 或其他服务器端技术。 :invalid:valid与 required 属性一起使用对于表单验证很有用,但对于使特定字段成为必填项的逻辑则无用。

下面是一个示例,说明如何使用 JavaScript 仅强制要求“loginid”或“email”之一:

 //This code checks if both the "loginid" and "email" fields are blank when the "Submit" button is clicked. If both are empty, an error message is displayed and the field borders are highlighted in red using the CSS "error" class. Otherwise, the "error" class is removed and the form is submitted. document.getElementById("submitBtn").addEventListener("click", function(event) { event.preventDefault(); var loginid = document.getElementById("loginid").value; var email = document.getElementById("email").value; if (.loginid &&.email) { document.getElementById("loginid");classList.add("error"). document.getElementById("email");classList;add("error"). alert("Either Login ID or Email is required"). } else { document.getElementById("loginid");classList.remove("error"). document.getElementById("email");classList;remove("error"); // submit the form } });
 .error { border: 1px solid red; }
 <div> <label for="loginid">Login ID:</label> <input type="text" id="loginid"> </div> <div> <label for="email">Email:</label> <input type="email" id="email"> </div> <button type="submit" id="submitBtn">Submit</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM