2009-09-23 179 views
2

我有3個HTML組合/下拉框。他們都有一個明確的名稱和ID。 在一個特定的事件中,我想要得到它們三個的價值。 任何人都可以給我一個代碼片段嗎?JavaScript:獲取下拉列表的值

+2

你知道「接受」按鈕? – Kamarey

+0

PLZ告訴我如何接聽答案。我只能看到commet按鈕。 很多人都要求我回答answe.But我不知道如何accpet.Where是選項 – user156073

+0

在你的問題的每一個答案,只是在票數下面,有一個像標誌的「v」。選擇你最喜歡的答案,然後按下這個「V」號。 – Kamarey

回答

5

使用jQuery:

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

使用一個框架像上面提到的jQuery或只是做了老同學的方式。 document.getElementById('dropdownId').value

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是你傳遞到函數值的陣列,如下所示:

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

如果<select>您指定的id之一不存在,該數組包含null作爲該位置的值。

有一對夫婦的其他方法可以做到這一點,你可以通過功能id值的數組:getSelectValues([ 'id1', 'id2', 'id3' ]),在這種情況下,函數就會改變:

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

您還可以通過功能地圖的id個和填充值:

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