我正在尝试在单击提交按钮时验证单选按钮中找到的值。我不确定正确的语法,这是我从目前为止在网上发现的内容拼凑而成的。
$(document).ready(function(){
alert('testing');
// Create array to traverse so that on clicking submit, the current question
//is deleted, and the next question in the array is loaded.
var questionsArray = [];
//Create counters for both correct answers and current question
var correctAnswers = 0;
var currentQuestion = 0;
//String to use for messages
var rightAnswer = "That's correct! You have " + correctAnswers + " out of 10 correct!";
var wrongAnswer = "Oh dear, that's so so wrong! You have " + correctAnswers + " out of 10 correct";
//Contructor Function to create questions
function Question (question, choices, answer){
this.question = question;
this.choices = choices;
this.answer = answer;
}
//Question Creations
questionsArray.push(new Question('Who is the Flash', ['Walter White', 'Johnny Cage', 'Barry Allen', 'Peter Parker'], 'Barry Allen'));
//Testing:
$('.q_question').append(questionsArray[0]['question']);
$('.btn1').after(questionsArray[0]['choices'][0]);
$('.btn2').after(questionsArray[0]['choices'][1]);
$('.btn3').after(questionsArray[0]['choices'][2]);
$('.btn4').after(questionsArray[0]['choices'][3]);
$('#submit').on('click', function(){
alert('click!'); //Test to make sure the click on submit is being recorded.
currentQuestion ++;
var answer = $('input[name="1"]:checked').val(); //The .val() is new to me, pretty sure this is where I've gone wrong
if(answer == questionsArray[0]['answer']){
correctAnswers ++;
$('.jumbotron').append(rightAnswer);
} else {
$('.jumbotron').append(wrongAnswer);
}
});
});
HTML:
<!doctype html>
<html>
<head lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href='css/css.css'>
<title>Super Awesome Quiz!</title>
</head>
<body>
<header class="header">
<h1 classs = "title">Welcome to My Super Awesome Quiz!!</h1>
<h3 class="question_counter">Ver. 1.1</h3>
</header>
<form class = "question">
<h2 class= "q_title"> </h2> <!-- Will use questionCounter here once created -->
<h3 class="q_question"></h3>
<input class='btn btn1' type="radio" name="1" value="answer" >
<br>
<input class='btn btn2' type="radio" name="1" value="answer" >
<br>
<input class='btn btn3' type="radio" name='1' value='answer' >
<br>
<input class='btn btn4' type="radio" name='1' value='answer' >
<br>
<input id="submit" type='submit' name='1' value='Submit'>
<br>
</form>
<div class='jumbotron'>
<h2></h2>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js.js" type="text/javascript"></script>
</body>
</html>
答案 0 :(得分:0)
问题是你没有更新无线电输入的值:
$('.q_question').append(questionsArray[0]['question']);
$('.btn1').after(questionsArray[0]['choices'][0]);
$('.btn1').val(questionsArray[0]['choices'][0]); // set value to option value
...
这将使输入值保持实际值,可以与正确答案进行比较。
另一种选择是与单选按钮后的文本值进行比较。