2009-08-07 1 views
31

を使用してオプションをどのように選択するかは、私は、このselect要素を含むHTMLフォームがあるとしましょう:私はプロトタイプ

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

は、どのように私は、オプションの要素のうちの1つを選択するために、プロトタイプを使用することができますか?

the API reference of Form.Elementにリストされている方法は、これをサポートしていないようです。

編集:「選択」とは、選択要素の「選択」属性と同じ効果を意味します。

答えて

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

optionsは、すべてのオプション要素の配列を#mySelectドロップダウンにしています。あなたが選択したとして、それらの一つ以上をマークしたい場合は、単に、現在選択されているオプション、使用を取得するには

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

を選択することになるので、基本的には$( "オプション1")だ=真の選択、右? –

+1

すべてのオプションにidが設定されている場合はyesのようにすることができます。 – RaYell

+0

ありがとう、私はこれを行うでしょう。 –

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

selectedプロパティを使用します。

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

私は '.attributes ['selected'] = true;が私の必要とするものだと思ったが、正しいコードは' .selected = true; 'だと思った。 – llamerr

+0

これはとても役に立ちました。 –

+0

'$( 'mySelect')。value'を使って値を取得できますか? – joshuahedlund

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

値で2番目のオプションを選択するためのあなたがこれを使用することができます

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

@JamesWiseman:prototype!= jQuery – mpen

-1

試してこれ...

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

はこれを試してみてください:

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

この1つはoption1

+0

ありがとう、魅力のように動作します!また、別の選択から選択した値を持つオプションを選択する場合は、次のようにします。 '$( 'select1')。setValue($( 'select2')。getValue())' – joseantgv

関連する問題