javascript - 下拉选择菜单,如何从出现的可选/其他文本框中检索值
问题描述
<script type="text/javascript">
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='Other: <input type="text" name="other" />';
else document.getElementById('div1').innerHTML='';
}
</script>
<select name="travel_arriveVia" id="travel_arriveVia" onchange="showfield(this.options[this.selectedIndex].value)">
<option selected="selected">Please select ...</option>
<option value="Plane">Plane</option>
<option value="Train">Train</option>
<option value="Own Vehicle">Own Vehicle</option>
<option value="Other">Other</option>
</select>
<div id="div1"></div>
这是我正在使用的代码,我不确定 DOM 操作是否会检索该值?无论我尝试什么,“其他”是提交时插入数据库的值,而不是在选择“其他”后出现的文本框中输入的可选文本。这是需要检索的。
解决方案
您可以使用document.querySelector('input[name="other"]')
name 获取文本框的值other
。由于不能保证此元素存在,因此您可以使用该if
条件来防止错误。为了说明这一点,querySelector
我使用了一个按钮,这样当您在文本框中输入值并单击该submit
按钮时,它将在控制台记录输入的值。您可以根据自己的情况使用它。
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='Other: <input type="text" name="other" />';
else document.getElementById('div1').innerHTML='';
}
function btnClick(){
var otherElem = document.querySelector('input[name="other"]');
if(otherElem){
console.log(otherElem.value);
}
}
<select name="travel_arriveVia" id="travel_arriveVia" onchange="showfield(this.options[this.selectedIndex].value)">
<option selected="selected">Please select ...</option>
<option value="Plane">Plane</option>
<option value="Train">Train</option>
<option value="Own Vehicle">Own Vehicle</option>
<option value="Other">Other</option>
</select>
<div id="div1"></div>
<button onclick='btnClick()'>Submit</button>