我有一个不属于我的网页,但我想获取一个SELECT元素的值。
例如:
<select name="ctl00$MainContent$CldFecha$DdlAnio" id="DdlAnio" class="calendarCombo2" onchange="ValidateYear();" style="width: 60px; display: none;" sb="83980340">
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option selected="selected" value="2015">2015</option>当我单击一个按钮时,我想要设置其中的任何选项,例如2013。
我知道如何获得选定的值,如下所示:
document.getElementById('DdlAnio').value而对于获取所选索引:
document.getElementById('DdlAnio').selectedIndex然而,我认为基于W3Schools,这些可能会设置所需的选项:
document.getElementById('DdlAnio').value = "2013"
document.getElementById('DdlAnio').selectedIndex = "2"但是什么都没有发生,我做错了什么吗?
我还尝试了:
document.getElementById('DdlAnio').options[DdlAnio.selectedIndex].value = 2013什么都不会发生
发布于 2015-12-23 03:57:47
我建议通过表单名称和元素名称来寻址。或者通过getElementById()。
function setOption1() {
document.form1['ctl00$MainContent$CldFecha$DdlAnio'].selectedIndex = 2;
}
function setOption2() {
document.getElementById('DdlAnio').selectedIndex = 2;
}<form name="form1">
<select name="ctl00$MainContent$CldFecha$DdlAnio" id="DdlAnio">
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option selected="selected" value="2015">2015</option>
</select>
<button onclick="setOption1()">setOption1</button>
<button onclick="setOption2()">setOption2</button>
</form>
发布于 2015-12-23 03:59:02
这个document.getElementById('DdlAnio').value = '2013';应该可以工作。
尝试临时删除onchange="ValidateYear();" (虽然不知道它实际做了什么)。
发布于 2015-12-23 04:01:16
在页面上创建一个按钮
<input type="button" onclick="setSelectTo('2012');" value="set year"/>为按钮创建onclick处理程序以获取值,该处理程序可以遍历选择框的选项并设置选定的索引。
function setSelectTo(yr) {
var selList = document.getElementById('DdlAnio');
for ( var i=0; i<selList.options.length; i++ ) {
if ( selList.options[i].value == yr ) {
selList.selectedIndex = i;
break;
}
}
}https://stackoverflow.com/questions/34423403
复制相似问题