简体   繁体   English

获取单选按钮的“ on”值

[英]Getting the value of “on” for radio buttons

 var allQuestions = [{ question1: "What is 1 + 1?", choices: ["1", "2", "3", 4], correctAnswer: ["2"] }, { question2: "What is 2 + 2?", choices: ["6", "2", "3", 4, ], correctAnswer: ["4"] }, { question3: "What is 3 + 3?", choices: ["3", "6", "9", 12], correctAnswer: ["6"] }]; var newArray = shuffleArray(allQuestions); function shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } function appendQuestions(number) { if (newArray == "undefined" || newArray == "null" || newArray.length == 0) { document.getElementById("questionForm").innerHTML = "Complete!"; } else { for (i = 0; i < 4; i++) { $("#questionForm").append("<input name='question' type='radio'>" + JSON.stringify(newArray[0].choices[i]) + "</input>") } } } $(function() { $("#questionList").empty(); appendQuestions(); newArray.shift(); }) function isCorrectAnswer() { checkedVal = $("input[type=radio][name=question]:checked").val(); if (checkedVal == newArray[0].correctAnswer) { alert("Correct!"); } else { alert("Wrong!"); } alert(checkedVal); } $("#submitButton").click(function() { isCorrectAnswer(); $("#questionForm").empty(); appendQuestions(); newArray.shift(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='container'> <section id='questions'> <form id="questionForm"> </form> <div style='clear:both'></div> <input id='submitButton' type='button' value='Submit'> </section> </div> 

First off, sorry for the amount of code pasted. 首先,对粘贴的代码量感到抱歉。 I have no idea if I'm missing some small bug or if I'm just writing the wrong code, so I figured it would be best to post all of it. 我不知道我是否遗漏了一些小错误,或者我只是在编写错误的代码,所以我认为最好将它们全部发布。

I am trying to get the value of a radio button. 我正在尝试获取单选按钮的值。 In the isCorrectAnswer function the first 2 lines are to determine the value of the radio button that is currently checked. 在isCorrectAnswer函数中,前两行用于确定当前选中的单选按钮的值。 The problem is when I alert the value of the radio button, it just says "on". 问题是当我警告单选按钮的值时,它只是说“开”。 I have searched for the last hour trying to figure out what this means or how to fix it and could not find a thing. 我搜索了最后一个小时,试图弄清这意味着什么或如何解决它,却找不到任何东西。

I apologize if this is a stupid question or if it has already been answered. 如果这是一个愚蠢的问题,或者已经被回答,我深表歉意。

You have to change this line : 您必须更改此行:

$("#questionForm").append("<input name='question' type='radio'>" +
         JSON.stringify(newArray[0].choices[i]) + "</input>");

To : 至 :

$("#questionForm").append("<input name='question' type='radio' value='" +
        JSON.stringify(newArray[0].correctAnswer[i]) + "' />"+JSON.stringify(newArray[0].choices[i]));

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM