<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function namereq(elem){
if(elem.value == 1){
var required = document.getElementById("name").attributes.required = true;}
}
if(elem.value == 0){
var required = document.getElementById("name").attributes.required = false;}
}
</script></head><body>
<p>Please select a detail level option.</p>
<select
required
id="toggle_detail"
name="toggle_detail"
oninput="namereq()">
<option disabled selected value> -- select an option -- </option>
<option value=1>Recommended</option>
<option value=0>Not Recommended</option>
</select>
<input
type="text"
id="name"
name="name"
placeholder="Name">
</body></html>
我正在尝试做什么...
默认输入id =“name”不是必需的。如果为id =“toggle_detail”问题选择了选项值= 1,则Javascript(不是JQuery)会将id =“name”的属性更改为required。否则,如果选择了Option Value = 2,Javascript将把id =“name”恢复为不需要。
请告知。
谢谢!
答案 0 :(得分:0)
请使用
document.getElementById(&#34; name&#34;)。required = true;
或者
document.getElementById(&#34; name&#34;)。required = false;