我有很多选择,如:
<select id="select1">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
<select id="select2">
<option value="1">asdf</option>
<option value="2" selected="selected">fdsa</option>
<option value="3">asdf</option>
</select>
我想在每个选项中选择一个选项,然后单击一个按钮,这些选项将存储到一个数组中,以便我可以稍后将其格式化为JSON。我有以下代码用于一个选项:
<button onClick="GetSelectedItem('select1');">Get Selected Item</button>
var arr1 = [];
function GetSelectedItem(el)
{
var e = document.getElementById(el);
var strSel =e.options[e.selectedIndex].text;
arr1.push(strSel);
console.log(arr1);
}
但我不知道怎么做超过1次选择。
答案 0 :(得分:3)
这对你有用。
function getSelectedItems() {
var elements = document.getElementsByClassName('selectVal');
var results = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var strSel = element.options[element.selectedIndex].text;
results.push(strSel);
}
console.log(results);
}
&#13;
<select id="select1" class="selectVal">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
<select id="select2" class="selectVal">
<option value="1">asdf</option>
<option value="2" selected="selected">fdsa</option>
<option value="3">asdf</option>
</select>
<button onClick="getSelectedItems()">Get Selected Item</button>
&#13;