2017-05-19 58 views
-2

我使用下面的代碼選擇陣列中的HTML檢索值如何從選擇陣列中的JavaScript

<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

的可能的複製[獲取使用JavaScript在下拉列表中選擇值?(http://stackoverflow.com/questions/ 1085801 /獲取選定值下拉列表使用JavaScript) – prasanth

+3

其中選擇?哪些值?更重要的是,你到目前爲止嘗試過哪些代碼? –

回答

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> 
+0

Thankyou,這工作:) – user2463053

-1

嘗試:

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

首先,您必須在選擇控件中分別添加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> 
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>