如何使用原型选择选项

31 html javascript prototypejs

假设我有一个包含此select元素的HTML表单:

  <select name="mySelect" id="mySelect">
    <option value="1" id="option1">1</option>
    <option value="2" id="option2">2</option>
  </select>
Run Code Online (Sandbox Code Playgroud)

如何使用原型选择其中一个选项元素?

Form.Element的API参考中列出的方法似乎对此没有帮助.

编辑:通过"选择"我的意思是"选定"属性对选项元素的等效效果.

RaY*_*ell 33

var options = $$('select#mySelect option');
var len = options.length;
for (var i = 0; i < len; i++) {
    console.log('Option text = ' + options[i].text);
    console.log('Option value = ' + options[i].value);
}
Run Code Online (Sandbox Code Playgroud)

options#mySelect下拉列表中所有选项元素的数组.如果要将其中一个或多个标记为选中,请使用selected属性

// replace 1 with index of an item you want to select
options[1].selected = true;
Run Code Online (Sandbox Code Playgroud)

  • 所以基本上它是$("option1").selected = true,对吧? (2认同)

Dav*_*tom 15

要获取当前选定的选项,请使用:

$$('#mySelect option').find(function(ele){return !!ele.selected})
Run Code Online (Sandbox Code Playgroud)


小智 8

nils petersohn几乎是正确的,但通常情况下,选项的"id"属性并不是人们所选择的.这个微小的变化使它成功.

var selectThis = 'option1';
$$('select#mySelectId option').each(function(o) {
  if(o.readAttribute('value') == selectThis) { // note, this compares strings
    o.selected = true;
    throw $break; // remove this if it's a multi-select
  }
});
Run Code Online (Sandbox Code Playgroud)


小智 7

试试这个:

$('mySelect').setValue(1); // or whatever value you want to select
Run Code Online (Sandbox Code Playgroud)

这个人会选择 option1