dpp*_*dpp 41 javascript selectedindex
如何使用显示文本作为参考设置select元素的selectedIndex?
例:
<input id="AnimalToFind" type="text" />
<select id="Animals">
<option value="0">Chicken</option>
<option value="1">Crocodile</option>
<option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
function SelectAnimal()
{
//Set selected option of Animals based on AnimalToFind value...
}
</script>
Run Code Online (Sandbox Code Playgroud)
没有循环,有没有其他方法可以做到这一点?你知道,我在想一个内置的JavaScript代码.另外,我不使用jQuery ...
Jac*_*kin 58
试试这个:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
<script type="text/javascript">
function SelectAnimal(){
//Set selected option of Animals based on AnimalToFind value...
var animalTofind = document.getElementById('AnimalToFind');
var selection = document.getElementById('Animals');
// select element
for(var i=0;i<selection.options.length;i++){
if (selection.options[i].innerHTML == animalTofind.value) {
selection.selectedIndex = i;
break;
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
设置select标签的selectedIndex属性将选择正确的项目.最好不要比较两个值(选项innerHTML && animal value),你可以使用indexOf()方法或正则表达式来选择正确的选项,尽管空格或空格的存在
selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
Run Code Online (Sandbox Code Playgroud)
或使用 .match(/regular expression/)
归档时间: |
|
查看次数: |
216428 次 |
最近记录: |