如何从javascript中的select数组中检索值

时间:2017-05-19 11:39:29

标签: javascript html

我在html中使用以下代码选择数组

<select name="selection[1]">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>
<select name="selection[2]">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

如何从javascript

中的此选择中检索值

4 个答案:

答案 0 :(得分:1)

您可以使用jQuery Attribute Starts With Selector [name^="value"]

$('[name^="selection"]').each(function() {
  console.log($(this).attr('name'));
  console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name="selection[1]">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>
<select name="selection[2]">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

答案 1 :(得分:0)

您可以为每个下拉列表提供ID并获取如下值:

<select name="selection[1]" id="selection1">
<option selected="selected">1</option>
<option>2</option>
<option>3</option>
</select>
<select name="selection[2]" id="selection2">
<option selected="selected">1</option>
<option>2</option>
<option>3</option>
</select>
<script>
var e = document.getElementById("selection1");
var strUser = e.options[e.selectedIndex].value;
console.log(strUser);
</script>

答案 2 :(得分:-1)

尝试:

document.getElementsByName('selection[1]')[0].value
document.getElementsByName('selection[2]')[0].value

答案 3 :(得分:-1)

首先,你必须分别在select控件中添加id =“selection [1]”和id =“selection [2]”,然后你可以调用这个函数来获取所选的值和文本。

<script>
function Getdropdown1()
{
var e = document.getElementById("selection[1]");
var selectedValue1 = e.options[e.selectedIndex].value;
var selectedText1 = e.options[e.selectedIndex].text;
}
</script>

<script>
function Getdropdown2()
{
var e = document.getElementById("selection[2]");
var selectedValue2 = e.options[e.selectedIndex].value;
var selectedText2 = e.options[e.selectedIndex].text;
}
</script>