HTML DOM Input Text required 属性
htmlweb developmentfront end technology更新于 2024/5/28 3:56:17
HTML DOM Input Text required 属性与 <input> 元素的 required 属性相关联。required 属性用于设置并返回在表单提交到服务器之前是否需要填写某些文本字段。如果用户将具有 required 属性的文本字段留空,则表单将无法提交。
语法
以下是语法 −
设置 required 属性 −
textObject.required = true|false
其中,true 表示必须填写文本字段,而 false 表示在提交表单之前可以选择是否填写该字段。
示例
让我们看一个 Input Text required 属性的示例 −
<!DOCTYPE html>
<html>
<body>
<h1>Input Text required property</h1>
<form action="/Sample_page.php">
USERNAME: <input type="text" id="USR" name=”user_name” required>
<input type="submit">
</form>
<p>Check if the above field is mandatory to be filled or not by clicking the below button</p>
<button onclick="checkReq()">CHECK</button>
<p id="Sample"></p>
<script>
function checkReq() {
var Req=document.getElementById("USR").required;
if(Req==true)
document.getElementById("Sample").innerHTML="The text field must be filled before submitting";
else
document.getElementById("Sample").innerHTML="The text field is optional and can be left blank by the user";
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击"检查"按钮后 −

如果您现在点击"提交"而不输入用户名,则会显示一条警告,并且不允许您提交表单 −

相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

