简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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