Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何设置单选按钮以使用其值进行检查_Javascript_Jquery_Arrays_Input_Checked - Fatal编程技术网

Javascript 如何设置单选按钮以使用其值进行检查

Javascript 如何设置单选按钮以使用其值进行检查,javascript,jquery,arrays,input,checked,Javascript,Jquery,Arrays,Input,Checked,我做了一个小测验: var allQuestions = { question: { question0: { question: "What is the meaning of HP?", choices: ["Hewlett-Pako", "Holy-Packard", "Hewlett-Packard", "Holy-Bigel"], correct: "Hewlett-Packard"

我做了一个小测验:

var allQuestions = {
    question: {
        question0: {
            question: "What is the meaning of HP?",
            choices: ["Hewlett-Pako", "Holy-Packard", "Hewlett-Packard", "Holy-Bigel"],
            correct: "Hewlett-Packard"
        },
        question1: {
            question: "how much is PI?",
            choices: ["2.54", "3.54", "1.21", "3.14"],
            correct: "3.14"
        },
        question2: {
            question: "Who is Messi?",
            choices: ["basketball player", "soccer player", "gold player", "tennis player"],
            correct: "soccer player"
        },
        question3: {
            question: "What is jQuery?",
            choices: ["JS library", "php library", "sql library", "html library"],
            correct: "JS library"
        }
    },

    correctAnswer: 0
};


function set_client() {//this function is to set the client info the first thing that the function does is to look if the text entered in the inputs is valid, next it will see if localstorage has been set already

    //the blur function test to see if the value entered in the inputs are text if it is then it will let you procced if not it wont let you go further more
    $("#fName,#lName").blur(function(){
        //check to see if the the info given is valid if not it will pop up a sentence that alert for wrong info
        var validfn = /[a-zA-Z]/.test($("input[name='fName']").val());// check to match the if the input is a-z char
        var validln = /[a-zA-Z]/.test($("input[name='lName']").val());// check to match the if the input is a-z char
        if (!validfn || !validln) {
            $("#log").append($("#fool").text("First name and last name must be a-z charcters").fadeIn());
            $("#fool").css({"margin-top":"-10px","margin-right":"-20px"});
        }
        else{ //if there the message already exist and the client entered valid text then the message will be dismiss
            $("#fool").fadeOut();
            return validfn;

        }
    }); //end of the blur function

    //checks to see if localStorage is already has vlaue.
    if (localStorage["fn"] == undefined) {
        $("#contain").hide();
        var data;
        //set the first name and last name to localstorage object for future used when clicking "login"
        $("#sublog").click(function () {
            var validfn1 = /[a-zA-Z]/.test($("input[name='fName']").val());// check to match the if the input is a-z char
            var validln1 = /[a-zA-Z]/.test($("input[name='lName']").val());// check to match the if the input is a-z char
            if (!validfn1 || !validln1) {
                //check blur function from above to see what validfn and valid ln does
            }
            else {
                data = { //and object to store the client firstname and lastname
                    first: $("input[name='fName']").val(),
                    last: $("input[name='lName']").val()
                }
                localStorage["fn"] = JSON.stringify(data["first"]);//client first name
                localStorage["ln"] = JSON.stringify(data["last"]);//client last name
            }
        });
    }
    //if there is already a value to localstorage then it means that someone has already logged in. in which this case it will show a welcome message including his first name and last name.
    else {
        $("#log").replaceWith("<h2>welcome : " + JSON.parse(localStorage['fn']) + " " + JSON.parse(localStorage['ln']) + "</h2>");
    }
}


var allquestion = allQuestions["question"];//just a quick way to access the object

var calcAnswers = allQuestions["correctAnswer"];//just a quick way to access the correctAnswer property object

var qNum = 0; //counts the questions up

var value; //undeclared var

var AnsW = [];

//function that display the question and the choices to the section.
function loadquestions(qNum) {
    if (allquestion["question" + qNum] != undefined) {
        $(".question").text(allquestion["question" + qNum]["question"]); //set the the question to the title
        for (var i = 0; i < allquestion["question" + qNum]["choices"].length;) {
            //loops throughout the li's
            var cH = (allquestion["question" + qNum]["choices"][i]); // a var that holds text of choice in poistion i
            $("label[for=li" + i + "]").text(cH); //define for every label its text
            $("#li" + i).attr("value", cH); //define for every input radio its value which is equals to label which is equals to var cH
            i++;//count i with +1
        }
    }
}
//function that fires when clicked the "next" button and when trigered hides the current question and presents the next one
function checkClientChoice() {
    $("#next").click(function () {
        value = $("input[type='radio']:checked").val(); //gets the value of the choosen radio buttons

        if (value == undefined) { //if the value is undefined throw an error and dont proceed to the next question
            $("#fool").fadeIn();
        }
        else {
            $("#back").css({"visibility":"visible"});
            if (allquestion["question" + qNum]["correct"] == value) { //if the value is same as the correct property in the allQuestions object then add +1 to calcAnswers and +1 to qNum and display the next question
                if ($("#fool").css({display: "block"})) {
                    $("#fool").hide();
                }
                $(".question,ul").fadeToggle(0.0000000001);
                calcAnswers++;
                qNum++;
                $(".question,ul").fadeToggle(1000);
                loadquestions(qNum);
            }
            else { //same here. if the value is not undefined but the client choosen answer is not correct then just count qNum up and load the next question but dont count calcAnswer +1
                if ($("#fool").css({display: "block"})) {
                    $("#fool").hide();
                }
                AnsW.push(value);
                $(".question,ul").fadeToggle(0.0000000000001);
                qNum++;
                $(".question,ul").fadeToggle(1000);
                loadquestions(qNum);
            }
        }
        result();
    });
};

function go_back(){
    $("#back").click(function(){
        qNum--;
        loadquestions(qNum);
        if(calcAnswers <= 0){
            calcAnswers = 0;
        }
        else{
            calcAnswers--;
        }
        var tempQuestion =  allquestion["question" + qNum]["question"];
        alert(tempQuestion);
        var tempAns = AnsW[qNum];//user last answer which is false i need this to make the radio button point to that answer
        alert( $("input[value=tempAns]"));
        $("input[value=tempAns]").is("checked",true);
        alert(tempAns);

        var tempAn = AnsW.splice(-1,1);//delete the false answer from the array i need this to make sure that the answer is deleted and there wont be overload of wrong answers
        alert(tempAn);
    });
}


function result() { //checks to see if the are no more questions to display
    if (allquestion["question" + qNum] == undefined) {
        $(".question").text("your Result is: " + calcAnswers + "/" + qNum);
        $("ul,#next,#back").hide();
    }
}

$(document).ready(function () {
    set_client();
    loadquestions(qNum);
    checkClientChoice();
    go_back();
});
var-allQuestions={
问题:{
问题0:{
问题:“HP的含义是什么?”,
选择:[“Hewlett Pako”、“Holy Packard”、“Hewlett Packard”、“Holy Bigel”],
更正:“Hewlett-Packard”
},
问题1:{
问题:“圆周率是多少?”,
选择:[“2.54”、“3.54”、“1.21”、“3.14”],
更正:“3.14”
},
问题2:{
问题:“梅西是谁?”,
选择:[“篮球运动员”、“足球运动员”、“金牌运动员”、“网球运动员”],
正确:“足球运动员”
},
问题3:{
问题:“什么是jQuery?”,
选项:[“JS库”、“php库”、“sql库”、“html库”],
更正:“JS库”
}
},
正确答案:0
};
函数set_client(){//此函数用于设置客户机信息。函数要做的第一件事是查看输入中输入的文本是否有效,然后查看是否已设置localstorage
//模糊功能测试,以查看输入中输入的值是否为文本如果是,则它将允许您继续,如果不是,则不会让您继续
$(“#fName,#lName”).blur(函数(){
//检查所提供的信息是否有效,如果无效,将弹出一句警告错误信息的句子
var validfn=/[a-zA-Z]/.test($($input[name='fName']).val();//如果输入是a-Z字符,请检查是否匹配
var validln=/[a-zA-Z]/.test($($input[name='lName']).val();//如果输入是a-Z字符,请检查是否匹配
如果(!validfn | |!validln){
$(“#log”).append($(“#傻瓜”).text(“名字和姓氏必须是a-z字符”).fadeIn();
$(“#傻瓜”).css({“页边顶部”:“-10px”,“页边右侧”:“-20px”});
}
else{//如果消息已经存在,并且客户端输入了有效文本,则消息将被删除
$(“傻瓜”).fadeOut();
返回validfn;
}
});//模糊函数的结尾
//检查本地存储是否已具有vlaue。
if(localStorage[“fn”]==未定义){
$(“#包含”).hide();
var数据;
//将名字和姓氏设置为localstorage对象,以便将来单击“登录”时使用
$(“#子日志”)。单击(函数(){
var validfn1=/[a-zA-Z]/.test($($input[name='fName']).val());//如果输入是a-Z字符,请检查以匹配
var validln1=/[a-zA-Z]/.test($($input[name='lName']).val());//如果输入是a-Z字符,请检查以匹配
如果(!validfn1 | |!validln1){
//从上面检查模糊功能,查看validfn和valid ln的功能
}
否则{
data={//和对象来存储客户机firstname和lastname
第一个:$(“输入[name='fName']”)。val(),
最后:$(“输入[name='lName']”)val()
}
localStorage[“fn”]=JSON.stringify(数据[“first”]);//客户端名称
localStorage[“ln”]=JSON.stringify(数据[“last”]);//客户端姓氏
}
});
}
//如果localstorage已经有一个值,则表示有人已经登录。在这种情况下,它将显示一条欢迎消息,包括他的名字和姓氏。
否则{
$(“#log”).replace为(“欢迎:”+JSON.parse(localStorage['fn'])+“”+JSON.parse(localStorage['ln'])+“”);
}
}
var allquestion=allQuestions[“问题”]//只是一种快速访问对象的方法
var calcAnswers=所有问题[“正确答案”]//这只是访问correctAnswer属性对象的快速方法
var qNum=0//把问题数一数
var值//未声明的var
var AnsW=[];
//函数,用于显示问题和部分的选项。
函数加载问题(qNum){
如果(所有问题[“问题”+qNum]!=未定义){
$(“.question”).text(allquestion[“question”+qNum][“question”];//将问题设置为标题
对于(变量i=0;i