输出所选按钮值或名称

时间:2016-11-08 04:13:59

标签: javascript

我正在尝试从按钮中获取值并在窗口中输出已选择的内容,对我来说,数组未定义

请帮助纠正我的错误。

<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 

4 个答案:

答案 0 :(得分:1)

您正在使用该值作为键。这就是它未定义的原因。

如果你做了flavorArray [2],它会给你“香草”。 但是你说索引是“香草”,所以它说未定义。

flavorValue将为您提供任何名为flavor

的元素

答案 1 :(得分: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

答案 2 :(得分:0)

在数组中查找选中的值。用户选择的value.its与数组的索引匹配。并使用受尊重的索引检索索引值。

&#13;
&#13;
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();
&#13;
<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()"/>
&#13;
&#13;
&#13;

答案 3 :(得分: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>