2016-11-08 2 views
0

ボタンから値を取得しようとしていますが、何が選択されているのか、私にとっては配列は未定義です。選択されたボタンの値または名前を出力しました

私の間違いを訂正してください。

<input type="radio" name="flavor" id="vanilla" value="Vanilla" checked="checked" />Vanilla 
<input type="radio" name="flavor" id="choc" value="Chocolate" />Chocolate 
<input type="radio" name="flavor" id="strawberry" value="Strawberry" />Strawberry 

var flavorArray = ["","","Vanilla","Chocolate","Strawberry"]; 

var flavorValue = document.querySelector('input[name = "flavor"]:checked').value; 

flavorArray[flavorvalue] -<< my output 

答えて

0

は、このコード試してみてください。

<html> 
    <head> 
     <title>Checkbox</title> 
    </head> 
    <body> 

     <input type="radio" name="flavor" id="vanilla" value="Vanilla" checked="checked"/>Vanilla 
     <input type="radio" name="flavor" id="choc" value="Chocolate" />Chocolate 
     <input type="radio" name="flavor" id="strawberry" value="Strawberry"/>Strawberry 


    <script> 

     var flavorArray = ["","","Vanilla","Chocolate","Strawberry"]; 
     var flavorValue = document.querySelector('input[name="flavor"]:checked').value; 

     console.log(flavorArray[flavorArray.indexOf(flavorValue)]) 
    </script> 
    </body> 
</html> 
1

値をキーとして使用しています。それが未定義の理由です。

flavorArray [2]を実行した場合は、 "Vanilla"と表示されます。 しかし、あなたはインデックスが「バニラ」だと言っているので、未定義と言っています。

flavorValueは、アレイ内にチェック値の場所を見つける名前風味

+0

をしかし、私はそれを行うだろうか、選択した一人のユーザーを知っているwouldntの?私がflavorarray [2]を置くと、それは私が書いたものを置くでしょう、どのボタンを選択してその値の名前を投稿することができますか? –

0
var flavorArray = ["","","Vanilla","Chocolate","Strawberry"]; 

var flavorValue = document.querySelector('input[name = "flavor"]:checked').value; 
console.log(flavorValue) //GIVES you the value 
console.log(flavorArray.indexOf(flavorValue)) //Gives you the index number of that value in your flavourArray if(-1) then value not exists 
0

を持っていることが確認されているものの要素あなたを与えるだろう。そして、ユーザーが選択したvalue.itsは、配列のインデックスと一致します。そして、尊重されたインデックスでインデックス値を取得します。

function check(){ 
 
    var flavorArray = ["","","Vanilla","Chocolate","Strawberry"]; 
 

 
var flavorValue = document.querySelector('input[name = "flavor"]:checked').value; 
 
for(var i=0; i<flavorArray.length; i++){ 
 
    if(flavorValue == flavorArray[i]) 
 
    {console.log('Matched index is' +i) 
 
     console.log('value is'+flavorArray[i]) 
 
    } 
 
    
 
    } 
 
    
 
    } 
 
check();
<input type="radio" name="flavor" id="vanilla" value="Vanilla" checked="checked" onclick="check()"/> 
 
<input type="radio" name="flavor" id="choc" value="Chocolate" onclick="check()"/> 
 
<input type="radio" name="flavor" id="strawberry" value="Strawberry" onclick="check()"/>

関連する問題