这是我的脚本,我的目标是如果在select中选择了其他,其他文本输入将被启用,这是我到目前为止,任何方法都会非常感激,我有4个问题像这样,我希望它是模块化的,最好的方法,使我的功能可以重复使用..如何正确地做这个没有任何问题发布我的数据,因为2名称输入将在PHP中生成2个帖子变量.. T_T
<script type="text/javascript" charset="utf-8">
function validate()
{
var ddl = document.getElementById("cause_pain");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "OTHER")
{
document.getElementsByClassName("causepain")[0].removeAttribute("name");
document.getElementsByClassName("causepain1")[0].removeAttribute("disabled");
}
}
</script>
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain" onchange="validate()">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain" name="cause_pain" size="40" onkeyup="clean('this.id')" disabled>
<input type="submit" id="submit"/>
</form>
答案 0 :(得分:0)
此方法可重复使用且非常直接。使用数据属性,您可以指定需要在特定选项元素上显示的元素。在显示任何输入元素之前,还要隐藏归因于上一个选择的元素。
示例:强>
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER" data-show="cause_pain_other">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain_other" name="cause_pain" size="40"
onkeyup="clean('this.id')" disabled style="display: none;">
<input type="submit" id="submit"/>
</form>
<script type="text/javascript" charset="utf-8">
var selectedOpt;
function selectionChanged(e) {
if (selectedOpt && selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = true;
showEl.style.display = 'none';
}
selectedOpt = this.querySelector('[value="'+e.target.value+'"]');
if (selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = false;
showEl.style.display = 'block';
}
}
document.querySelector('select').addEventListener('change', selectionChanged);
</script>
如果您在同一页面上使用多个选项,然后只需将该元素作为索引添加到对象,那么您的selectedOpt
应该是一个对象:
var selectedOpt = {};
...
selectedOpt[this.id] = this.querySelector('[value="'+e.target.value+'"]');