2

3 つの HTML コンボ/ドロップダウン ボックスがあります。それらはすべて、固有の名前と ID を持っています。特定のイベントで、3 つすべての値を取得したいと考えています。そのためのコードスニペットを教えてもらえますか?

4

4 に答える 4

5

jQueryを使用:

$("#dropdownID").val(); 
于 2009-09-23T08:44:24.837 に答える
1

HTML でそれらを並べて設定し、jQuery の組み込みの each() メソッドを使用してそれらを反復処理します。次のように要素を設定します。

<div id="dropdownBoxes">
<select id="firstElement">
    <option>cool</option>
    <option>neat</option>
</select>
<select id="secondElement">
    <option>fun</option>
    <option>awesome</option>
</select>
<select id="thirdElement">
    <option>great</option>
    <option>synonym</option>
</select>
</div>

<input type="button" id="theTrigger">Push me!</input>

次に、スクリプトで次のようにします。

var dropdownValues;

$("#theTrigger").click(function(){    
dropdownValues.length=0;
$("#dropdownBoxes select").each(function(){
    dropdownValues.push($(this).val());
    });
});
于 2010-05-17T07:29:54.043 に答える
1

jQueryを使用せずにこれを行うには:

function getSelectValues() {
    var values = [];
    for (var i = 0; i < arguments.length; i++) {
        var select = document.getElementById(arguments[i]);
        if (select) {
            values[i] = select.options[select.selectedIndex].value;
        } else {
            values[i] = null;
        }
    }
    return values;
}

idこの関数は、次のように、関数に渡す s に対応する値の配列を返します。

var selectValues = getSelectValues('id1', 'id2', 'id3');

<select>指定idした s のいずれかを持つ が存在しない場合、配列にはその位置の値が含まれnullます。

これを行うには他にもいくつかの方法があります。関数にid値の配列を渡すことができます: getSelectValues([ 'id1', 'id2', 'id3' ])。この場合、関数は変更されます。

function getSelectValues(ids) {
    var values = [];
    for (var i = 0; i < ids.length; i++) {
    // ...

id関数にs のマップを渡し、値を設定することもできます。

var myMap = { 'id1': null, 'id2': null, 'id3': null };
getSelectValues(myMap);
// myMap['id1'] contains the value for id1, etc

これにより、関数は次のように変更されます。

function getSelectValues(map) {
    for (var id in map) {
        var select = document.getElementById(id);
        if (select) {
            map[id] = select.options[select.selectedIndex].value;
        } else {
            map[id] = null;
        }
    }
}
于 2009-09-30T15:51:11.133 に答える
0

上記のjQueryのようなフレームワークを使用するか、古い学校の方法でそれを行ってください。document.getElementById('dropdownId').value.

于 2009-09-30T15:47:04.243 に答える