这肯定已经被覆盖过了,并且肯定会再次出现,但是我发现的所有例子都没有帮助我。
我有一个下拉字段,当选择选项2(Admin)时,我想显示一种隐藏的文本输入类型。
const ac = document.getElementById("admin_code");
ac.style.display = "none";
function toggleDropdown(selObj){
ac.style.display = selObj.value === "Admin" ? "block" : "none";
}
<label>User Type:</label> <select id="userType" name="userType" id="userType" onchange='toggleDropdown(this);' required>
<option value="" selected>Select User Type</option>
<option value="Client">Client</option>
<option value="Admin">Admin</option>
<option value="Staff">Staff</option>
</select>
<br>
<div id="admin_code">
<label>Person Code:</label> <input type="text" name="adminCode"
id="adminCode" placeholder="000001">
</div>
当前,当我进入页面时,我的admin_code div将从头开始显示。我尝试将style.display值都更改为none,以查看是否甚至被调用,但似乎没有。
答案 0 :(得分:2)
将this
关键字传递到您的回调函数中:
const ac = document.getElementById("admin_code");
ac.style.display = "none";
function toggleDropdown(selObj) {
ac.style.display = selObj.value === "Admin" ? "block" : "none";
}
<label>User Type:</label>
<select id="userType" name="userType" id="userType" onchange='toggleDropdown(this);' required>
<option value="" selected>Select User Type</option>
<option value="Client">Client</option>
<option value="Admin">Admin</option>
<option value="Staff">Staff</option>
</select>
<br>
<div id="admin_code">
<label>Admin Code:</label> <input type="text" name="adminCode" id="adminCode">
</div>
答案 1 :(得分:0)
这对我有用。首先,我将div#admin_code的初始样式设置为“ display:none;”
然后我稍微更改了您的功能
function toggleDropdown(){
let value = document.querySelector('select').value;
if (value=="Admin") {
document.getElementById("admin_code").style.display = "block";
} else {
document.getElementById("admin_code").style.display = "none";
}
}
<label>User Type:</label> <select id="userType" name="userType" id="userType" onchange='toggleDropdown();' required>
<option value="" selected>Select User Type</option>
<option value="Client">Client</option>
<option value="Admin">Admin</option>
<option value="Staff">Staff</option>
</select>
<br><div id="admin_code" style="display: none;">
<label>Admin Code:</label> <input type="text" name="adminCode" id="adminCode" >
</div>