[英]javascript set selected for select option
I am dynamically generating dropdowns egsomeDropDown0, someDropDown1, someDropDown2 ...etc and write it a div in page . 我正在动态生成下拉列表,例如someDropDown0,someDropDown1,someDropDown2 ... etc,并将其写入page中的div中。 I want to know how can set the "selected" option value to onChange of the drop.
我想知道如何将“选择的”选项值设置为拖放的onChange。
The reason when i add a new drop down via button the value of old one is resetted to "Select one". 我通过按钮添加新下拉列表时,将旧的值重置为“选择一个”的原因。
Need a onChange which will set the selected value as "Selected" so the selected values stays there. 需要一个onChange,它将选择的值设置为“ Selected”,以便选择的值保持在那里。
<select id="someDropDown0" onChange=setVak(this, this.id)>
<option value="Select One" selected>Select One</option>
<option value="12">AB</option>
<option value="13">CD</option>
<option value="15">EF</option>
<option value="20">GH </option>
<option value="21">IJ </option>
<option value="22">LM </option>
</select>
function setval(optionVal, optionId)
{
var dd = document.getElementById(optionId);
for (var i = 0; i < dd.options.length; i++)
{
if (dd.options[i].text === optionVal.text)
{
dd.selectedIndex = i;
break;
}
}
}
Please help. 请帮忙。 Thanks
谢谢
Setting the defaultSelected property of the appropriate option element to true should do the trick: 将适当的option元素的defaultSelected属性设置为true应该可以解决问题:
> if (dd.options[i].text === optionVal.text)
> {
dd.options[i].defaultSelected = true;
> dd.selectedIndex = i;
> break;
> }
But make sure you only have one option with it set. 但是请确保只设置了一个选项。
Or did I completely misunderstand the question? 还是我完全误解了这个问题?
If I got you right and you are adding new options to an existing select box: rather than an some kind of "onchange" behaviour (subtree modification actually), your may want to alter the code that appends new select options. 如果我理解正确,并且您要向现有的选择框添加新选项:而不是某种“ onchange”行为(实际上是对子树的修改),则可能需要更改附加新选择选项的代码。
See these example functions for reference: 请参阅以下示例函数以供参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.