質問

私は箱をドロップダウン/ 3 HTMLコンボを持っています。それらのすべては、異なる名前とIDを持っています。 特定のイベントで、私はそれらのすべての3つの値を取得したいです。 いずれかは私にそのためのコードスニペットを与えることができますか?

役に立ちましたか?

解決

のjQueryを使用します:

$("#dropdownID").val(); 

他のヒント

私はあなたのHTMLで隣同士にそれらを設定して、jQueryの組み込みの各()メソッドを使用して、それらを反復処理しようと思います。

:あなたはこのようなあなたの要素を設定したいです
<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());
    });
});

の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;
}
次のように

この関数は、関数に渡すidsに対応する値の配列を返す

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

あなたの指定<select>sの一つとidアレイは、その位置の値のためnullが含まれている存在しない場合ます。

id、機能が変更されるであろう場合には:これを行うには、他のいくつかの方法があります。

は、関数getSelectValues([ 'id1', 'id2', 'id3' ])値の配列を渡すことができます。

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

また、関数にidsのマップを渡し、値を移入できます:

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

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top