我想通过添加必需的属性来强制选择一个选项,但它似乎不起作用。据我看来,它在语法上是正确的。请帮我。提前致谢。
function func() {
var a = document.getElementById("input").value;
if (a === "SE-IT-A" || a === "SE-IT-B") {
var arr = ["Choose Subject", "DBMS", "DSA"];
} else if (a === "TE-IT-A" || a === "TE-IT-B") {
var arr = ["Choose Subject", "CNS", "ADMT"];
}
var string = "";
for (i = 0; i < arr.length; i++) {
string = string + "<option>" + arr[i] + "</option>";
}
string = "<select required name='second'>" + string + "</select>";
document.getElementById("output").innerHTML = string;
}
<form>
<select name="class" id="input" onchange="func()" required>
<option value="">Choose Class</option>
<option value="SE-IT-A">SE-IT-A</option>
<option value="SE-IT-B">SE-IT-B</option>
<option value="TE-IT-A">TE-IT-A</option>
<option value="TE-IT-B">TE-IT-B</option>
</select><br>
<div id="output"></div>
</form>
最佳答案
required
仅当您获得一个包装 select 元素的表单并具有 button
时,属性才起作用。 (或 input
)其类型为 submit
处理表单提交操作。
<form>
<select required>
<option> any thing </option>
</select>
<button type="submit"> Submit the form </button>
</form>
当您单击提交按钮时,浏览器将警告您选择字段是必需的。由于您使用的是自定义 js 处理程序,因此您不会收到浏览器警告。
拿Form data validation作为引用,搜索The required attribute
部分了解详细信息。
关于javascript - 为什么 JavaScript 创建的 <select> 的 "required"属性无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58472549/