所以我目前有一个select
字段,如下所示:
<select id = "foo">
<option value = "example">This example</option>
<option value = "example2">This example Again</option>
<option value = "bar">This is just a bar</option>
</select>
如果提交的表单返回错误,它会将对象中的所有值发回给我,我需要重新填充表单。
我的问题:如何有效地获取值bar
的索引,而不必使用jQuery?
有没有办法在不必遍历每个选项的情况下执行此操作,根据我的选项检查值,然后将其设置为已选中,如果它与我的值相同?
非常感谢任何见解
答案 0 :(得分:5)
您可以将querySelector()
与index
合并:
var selected = document.querySelector( '#foo > option[value="bar"]' );
console.log(selected.index);