javascript输入字段返回“ on”,而不是控制台中的值

时间:2019-06-25 10:09:44

标签: javascript ecmascript-6

我在JavaScript中遇到问题。 提交表单时,我想从一系列单选按钮中获取值。
但是我总是得到on的值,而不是应该是“ A”,“ B”或“ C”的值,我不知道为什么它如此。

这是js

const questionContainer = document.querySelector('#js-question-container');

const quizz = document.querySelector('.js-quizz');

const result = document.querySelector('.js-score');

const getQuestions = (callback) => {
    const request = new XMLHttpRequest();
    request.addEventListener('readystatechange', (() => {
        // console.log(request, request.readyState);
        if (request.readyState === 4 && request.status === 200) {
            const data = JSON.parse(request.responseText);
            callback(undefined, data);

        } else if (request.readyState === 4) {
            callback("Les données n'ont pas pu etre chargées", undefined);
        }

    }))
    request.open('GET', './questions.json');
    request.send();
}

getQuestions((err, data) => {
    console.log('callback fired !');
    console.log(err, data);

    let output = '';
    data.forEach(question => {
        output += `<p class="lead">${question.title}</p>`;
        question.answers.forEach(answer => {
            output += `<div class="form-check ${answer.value}">
            <input type="radio" class="form-radio answer${question.id}" name="q${question.id}" "value=${answer.value} ${shouldBeChecked(answer.id)}>
                <label class="form-check-label" for= "q${question.id}">${answer.sentence}</label>
        </div >`;
        });
        questionContainer.innerHTML = output;
        tryToDelegate();
        formSubmission(question);
    })
});

const formSubmission = (question) => {

    quizz.addEventListener('submit', e => {
        e.preventDefault();
        let score = 0;
        const userAnswers = [quizz.q0.value, quizz.q1.value, quizz.q2.value, quizz.q3.value];

        console.log('useranswers',userAnswers[3]);
        const correctAnswers = ["A", "B", "B", "B"];
        const nbQuestions = correctAnswers.length;
        let commentText = document.querySelector('.js-comment-text');

        userAnswers.forEach((answer, index) => {
            if (answer === correctAnswers[index]) {
                score += 1 / nbQuestions;
            }
            console.log('answer',answer, score);
            result.classList.remove('d-none');
            switch (score * 100) {
                case 0:
                    commentText.textContent = "Flatten by the ninja";
                    scrollToTop();
                    break;
                case 25:
                    commentText.textContent = "That's a pity score, please improve !";
                    scrollToTop();
                    break;
                case 50:
                    commentText.textContent = "On the way to the success !";
                    scrollToTop();
                    break;
                case 75:
                    commentText.textContent = "You nearly beat the ninja !";
                    scrollToTop();
                    break;
                case 100:
                    commentText.textContent = "The ninja is KO !";
                    scrollToTop();
                    break;
                default:
                    commentText.textContent = '';
            }

            let outputScore = 0;
            const timer = setInterval(() => {
                result.querySelector('.js-score-inner').innerHTML = `Your score is < span class="display-4 text-primary" > ${outputScore} %</span > `;
                if (outputScore === (score * 100)) {
                    clearInterval(timer)
                } else {
                    outputScore++;
                }

            }, 10);
        });
    })
}

let scrollToTop = () => {
    const topXOffset = document.querySelector('#top').offsetLeft;
    const topYOffset = document.querySelector('#top').offsetTop;

    window.scrollTo(topXOffset, topYOffset);
}
const tryToDelegate = () => {
    quizz.querySelectorAll('.form-check').forEach(item => {
        item.addEventListener('click', () => {
            item.querySelector('input[type="radio"]').setAttribute('checked', 'checked');
            var el = item.nextElementSibling;
            console.log(el);
        });
    })
}
const shouldBeChecked = element => {
    if (element === 0) {
        return 'checked';
    } else {return '';}
}

还有html文件

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Quizz</title>
    <meta name="description" content="">
    <meta name="viewport" content="wvalueth=device-wvalueth, initial-scale=1">
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./quizz.css">
</head>

<body>
    <div>
        <header class="intro py-3 bg-white text-center" id="top">
            <div class="container">
                <h2 class="text-primary display-3 my-4">Ninja quizz</h2>
            </div>
        </header>

        <div class="text-center py-4 js-score d-none bg-light">
            <div class="container lead">
                <span class="js-score-inner"></span>
                <p class=""><em class="js-comment-text"></em></p>
            </div>
        </div>
        <div class="questions py-4 bg-primary">
            <div class="container">
                <form class="js-quizz">
                    <div class="question text-white" id="js-question-container">
                    </div>
                    <div class="text-center"><input type="submit" value="Submit" class="btn btn-light"></div>
                </form>
            </div>
        </div>
    </div>
<script src="./quizz.js" async defer></script>
</body>

</html>

请注意,该项目会获取一个本地JSON文件(这很正常),然后根据JSON文件提供的数据呈现一个表单。

1 个答案:

答案 0 :(得分:1)

在第34行对我来说,您有问题;

name =“ q $ {question.id}”“ value = $ {answer.value} $ {shouldBeChecked(answer.id)}-价值问题

name =“ q $ {question.id}” value =“ $ {answer.value} $ {shouldBeChecked(answer.id)”}应该是