如何使用原型选择选项

32

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

  <select name="mySelect" id="mySelect">
    <option value="1" id="option1">1</option>
    <option value="2" id="option2">2</option>
  </select>

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

Form.Element的API参考文档中列出的方法似乎不能帮助解决这个问题。

编辑:通过“select”,我指的是在选项元素上使用“selected”属性的等效效果。

9个回答

34
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);
}

options#mySelect下拉菜单中的所有选项元素的数组。如果你想将其中一个或多个标记为已选,则只需使用selected属性即可。

// replace 1 with index of an item you want to select
options[1].selected = true;

1
如果您为所有选项设置了ID,则可以像这样操作。 - RaYell
1
@PatB 在原型中,这是如何使用 CSS 选择器获取元素的方式,只需要 $ 就相当于 getElementById()。 - Alexxandar

15

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

$$('#mySelect option').find(function(ele){return !!ele.selected})

我原以为 .attributes['selected'] = true; 是我需要的代码,但正确的代码是 .selected = true; - llamerr
1
你可以直接使用 $('mySelect').value 来获取值吗? - joshuahedlund

9

试试这个:

$('mySelect').setValue(1); // or whatever value you want to select

这个会选择选项1


谢谢,运行得很好!如果你想从另一个选择器中选择一个具有选定值的选项,请使用:$('select1').setValue($('select2').getValue()) - joseantgv

8

尼尔斯·彼得索恩几乎做对了,但通常情况下,选项的“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
  }
});

1

如果要按值选择第二个选项,您可以使用以下代码:

var myChoice = '2';

$$('select#mySelectId option').each(function(o) {
    o.selected = o.readAttribute('value') == myChoice;
});

1
var itis = $(mySelectId).select('option[value="' + sValueToSelect + '"]');
if ( itis && itis.length > 0 )
    itis[0].selected = true;

1

假设您知道要选择的值,请尝试:

$('mySelect').value = 2; // 2 being the value you want selected

0
var selectThis = 'option1';
$$('select#mySelect option').each(function(o){
      if(o.id==selectThis){o.selected = true;$break;}
});

-1

试一下这个...

document.observe('dom:loaded', function() {
   $('mySelect').observe('change', function(event) {
    ...
   });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接