使用Jquery从Radio获取价值

时间:2013-10-28 23:47:08

标签: jquery jquery-selectors radio-button

我正在寻找一种从单选按钮获取价值的方法。我在这里有html。

<div id="main_">
    <div class="facts_div">
        <span class="question"></span>
        <ul></ul>
    </div>
    <div id = "next_button">
    <form>
        <input id="x" type="button" class="myBtn" value="Press Me">
    </form>
    </div>
</div>
</div>

这是Jquery代码。

$(document).ready (function () {

//

var answers = 
[["Fee","Fi","Fo"], 
["La","Dee","Da"]],
questions = 
["Fee-ing?",
"La-ing?"],
corAns = ["Fee", "La"];

var counter = 0;
var correctAnswers = 0;

var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');


$btn.on('click', function() {
    if (counter < questions.length) {
        $question.text(questions[counter]);

        var ansstring = $.map(answers[counter], function(value) {
            return '<li><input type="radio" name="ans" value="0"/>'
            + value + '</li>'}).join('');
        $ul.html(ansstring);
        alert($('input[name="ans"]:checked').val())
        //if ($('input[name=ans]:checked').val() == corAns[counter]) {
            //correctAnswers++;
        //}
    }
    else {
        $facts.text('You are done with the quiz ' + correctAnswers);
        $(this).hide()
    }
    counter++;
});



//    
});

正如你所知,它一直未定义返回,我不太确定我做错了什么。

顺便提一下,值是在我正在进行的测验中衡量这是正确答案还是不正确答案。所以,最终我需要在if语句中使用array[counter]。但是,我把它分开来测试和调整并弄清楚如何获得价值。

1 个答案:

答案 0 :(得分:0)

我相信你做的比现在要复杂得多。你只需要一组正确的答案,然后点击按钮就可以循环查看答案(你会在评论中看到游戏):

$btn.on('click', function() {
    //Your answers array should never be longer than your questions length, so that check is a bit useless, scrap it
    //Lets first gather all your answers into an array, the .map function is built for this:

    var currentAnswers = $('input[name="ans"]:checked').map(function() {
        return this.value;
    }).get();

    //Now that we have all the checked radio buttons from the quiz, loop and compare to your answers array, if they match, do something
    //You have a 2D array of answers, then one of correct answers, you only need 1 array, and that should contain the correct responses, so eliminate the 2D array
    //Your correct answers should be: corAns = ["Fee", "La"];

    var correct = 0; //current number of correct answers
    for (var i = 0; i < currentAnswers.length; i++) {
        if (currentAnswers[i] == corAns[i]) {
            correct++; //Increment correct variable
        }
    }
});

当然,您可能需要检查以确保用户已经回答了所有问题,否则最终数组可能会超出范围并导致错误。