2016-08-16 1 views
-2

私は配列に入れたい選択肢を持っていますが、ボタンをクリックしたときに特定のメッセージを警告しようとしていますが、適切な配列[x]が選択されている場合に限ります。しかし、ボタンをクリックすると、オプションに関係なくメッセージが表示されます。私は間違って何をしていますか?JS配列の選択を警告する

コード:

HTML:

<button id="button">Click Me</button> 
<br /> 
<br /> 
<select id = "list" value = "list"> 
    <option id="one" value="one"> 
    one 
    </option> 

    <option id="two" value="two"> 
    two 
    </option> 

    <option id="three" value="three"> 
    three 
    </option> 
</select> 

JS:

var listArr = []; 
var button = document.getElementById("button"); 
var list = document.getElementById("list"); 
var selected = document.getElementById("list").selectedIndex; 

for (var i = 0; i < list.options.length; i++) { 
    listArr[i] = list.options[i].value; 
} 

button.onclick = function() { 
    if (selected = [1]) { 
     alert("hello"); 
    } 
}; 
+1

を '場合とは何ですか(=選択された[1]){ ...} 'ステートメント? – Titus

+0

あなたが間違っている、おそらくそれが '(選択された=== listArr [1])'になることを望んでいた –

答えて

4

あなたはこのような配列を比較することはできません。代わりにリテラル番号を使用する必要があります。 JSFiddle

var listArr = []; 
var button = document.getElementById("button"); 
var list = document.getElementById("list"); 
var selected = document.getElementById("list"); 

for(var i = 0; i < list.options.length; i++) { 
    listArr[i] = list.options[i].value; 
} 

button.onclick = function() { 
    if(selected.selectedIndex == 1) { 
    alert('hello'); 
    } 
}; 
+0

興味深い!どうもありがとう! –

0

私が正しくあなたの質問を理解している場合は、選択の更新された値が必要です。

button.onclick = function() 
{ 
    if(document.getElementById("list").selectedIndex==1) // Also change = to == 
    { 
    alert("hello"); 
    } 
}; 

https://jsfiddle.net/6bs1vjva/1/

関連する問題