[英]Make either one HTML input field required using CSS
Is it possible to make either loginid
or email
as required, just by using CSS or HTML (instead of using Javascript)?是否可以根据需要制作
loginid
或email
,只需使用 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>
Sorry, but it is not possible to use only CSS and HTML to make only one of the two fields "loginid" or "email" mandatory.抱歉,不可能仅使用 CSS 和 HTML 来使“loginid”或“email”这两个字段中的一个成为必填字段。
This type of functionality would require the use of JavaScript or other server-side technologies.这种类型的功能需要使用 JavaScript 或其他服务器端技术。 Using
:invalid
and :valid
with the required attribute is useful for form validation, but not for the logic of making specific fields mandatory.将
:invalid
和:valid
与 required 属性一起使用对于表单验证很有用,但对于使特定字段成为必填项的逻辑则无用。
Here is an example of how to make only one of "loginid" or "email" mandatory using JavaScript:下面是一个示例,说明如何使用 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.