Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 05.05.2020, 00:59
Новичок на форуме
Отправить личное сообщение для RIMINI Посмотреть профиль Найти все сообщения от RIMINI
 
Регистрация: 09.11.2019
Сообщений: 2

Рандом вопросов мини-теста
Здравствуйте!
У меня есть программа теста. Как мне сделать так, чтобы вопросы каждый раз были в разном порядке?
<h2>Тестирование</h2>
<div class="jumbotron"> <hr />
    <div id="question1" style=" display:block;">
        <p>Вопрос 1</p>
        <p><span id="quest_1"></span> <input type="text" onkeyup="check();" id="answer_1"></p></div>
    <div id="question2" style=" display:none;">
        <p>Вопрос 6</p>
        <p><span id="quest_2"></span> <input type="text" onkeyup="check();" id="answer_2"></p> </div>
    <div id="question3" style=" display:none;">
        <p>Вопрос 3</p>
        <p><span id="quest_3"></span> <input type="text" onkeyup="check();" id="answer_3"></p></div>
    <div id="question4" style=" display:none;">
        <p>Вопрос 4</p>
        <p>
            <span id="quest_4"></span><br />
            <input type="radio" name="q_4" value="1" onkeyup="check();" id="answer_4" /><span>ответ1</span><br>
            <input type="radio" name="q_4" value="0" onkeyup="check();" id="answer_4" /><span>ответ2</span><br>
            <input type="radio" name="q_4" value="0" onkeyup="check();" id="answer_4" /><span>ответ3</span> </p></div>
    <div id="question9" style=" display:none;">
        <p>Вопрос 5</p>
        <p><span id="quest_5"></span><br />
            <input type="radio" name="q_5" value="1" onkeyup="check();" id="answer_5" /><span> ответ1</span><br>
            <input type="radio" name="q_5" value="0" onkeyup="check();" id="answer_5" /><span>ответ2</span><br>
            <input type="radio" name="q_5" value="0" onkeyup="check();" id="answer_5" /><span> ответ3</span></p></div>
    <div id="question6" style=" display:none;">
    <button id="but_next" class="btn btn-default" disabled="disabled" onclick="next_question();">Следующий вопрос</button>
    <button id="but_verify" style="display:none;" class="btn btn-default" onclick="verify();">Проверить</button>

    <div id="rezult"></div>

</div>


<script>

    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('quest_1').innerHTML = question_1;
        document.getElementById('quest_2').innerHTML = question_2;
        document.getElementById('quest_3').innerHTML = question_3;
        document.getElementById('quest_4').innerHTML = question_4;
        document.getElementById('quest_5').innerHTML = question_5;
    })

    function next_question() {
        if (document.getElementById('question5').style.display == "block") {
            document.getElementById('question5').style.display = "none";
            document.getElementById('question6').style.display = "block";
            document.getElementById('but_next').disabled = true;
document.getElementById('but_next').style.display = "none";
            document.getElementById('but_verify').style.display = "block";
        }
        if (document.getElementById('question4').style.display == "block") {
            document.getElementById('question4').style.display = "none";
            document.getElementById('question5').style.display = "block";
            document.getElementById('but_next').disabled = true;
        }
        if (document.getElementById('question3').style.display == "block") {
            document.getElementById('question3').style.display = "none";
            document.getElementById('question4').style.display = "block";
            document.getElementById('but_next').disabled = true;
        }
        if (document.getElementById('question2').style.display == "block") {
            document.getElementById('question2').style.display = "none";
            document.getElementById('question3').style.display = "block";
            document.getElementById('but_next').disabled = true;
        }
        if (document.getElementById('question1').style.display == "block") {
            document.getElementById('question1').style.display = "none";
            document.getElementById('question2').style.display = "block";
            document.getElementById('but_next').disabled = true;
        }
    }

    function check() {
        if ($('input[id^="answer_"]').val() != '')
            $('#but_next').removeAttr('disabled');
        else $('#but_next').attr('disabled', 'disable');
        $("input[type=radio]").on("change", function () {
            $("button").prop("disabled", false);
        });
    }
    function verify() {
        answ_1 = document.getElementById('answer_1').value;
        answ_student_1 = answ_1;
        answ_1 = kodirov(answ_1);

        answ_2 = document.getElementById('answer_2').value;
        answ_student_2 = answ_2;
        answ_2 = kodirov(answ_2);

        answ_3 = document.querySelector('input[id="answer_3"]:checked').value;
        answ_student_3 = document.querySelector('input[id="answer_3"]:checked').nextElementSibling.innerText;

        answ_4 = document.querySelector('input[id="answer_4"]:checked').value;
        answ_student_4 = document.querySelector('input[id="answer_4"]:checked').nextElementSibling.innerText;

        answ_5 = document.querySelector('input[id="answer_5"]:checked').value;
        answ_student_5 = document.querySelector('input[id="answer_5"]:checked').nextElementSibling.innerText;

        count = 0;
        count_theory = 0;
        count_practice = 0;
        ball = 0;

        document.getElementById('question10').style.display = "none";
        document.getElementById('but_verify').style.display = "none";
        if (answ_1 == correct_answer_1) {
            count++;
            all_answers += "<br><span id='vo'>Вопрос 1." + question_1 + "<br>Ваш ответ: " + answ_student_1 + "<br>Вы ответили верно" + "</span><br>";
        } else {
            all_answers += "<br><span id='nvo'>Вопрос 2.Вы ответили не верно" + "</span><br>";
        }
        if (answ_2 == correct_answer_2) {
            count++;
            all_answers += "<br><span id='vo'>Вопрос 2." + question_2 + "<br>Ваш ответ: " + answ_student_2 + "<br>Вы ответили верно" + "</span><br>";
        } else {
            all_answers += "<br><span id='nvo'>Вопрос 2.Вы ответили не верно" + "</span><br>";
        }
        if (answ_3 == correct_answer_3) {
            count++;
            all_answers += "<br><span id='vo'>Вопрос 3." + question_3 + "<br>Ваш ответ: " + answ_student_3 + "<br>Вы ответили верно" + "</span><br>";
        } else {
            all_answers += "<br><span id='nvo'>Вопрос 3.Вы ответили не верно" + "</span><br>";
        }
        if (answ_4 == '1') {
            count++;
            all_answers += "<br><span id='vo'>Вопрос 4." + question_4 + "<br>Ваш ответ: " + answ_student_4 + "<br>Вы ответили верно" + "</span><br>";
        } else {
            all_answers += "<br><span id='nvo'>Вопрос 4.Вы ответили не верно" + "</span><br>";
        }
        if (answ_5 == '1') {
            count++;
            all_answers += "<br><span id='vo'>Вопрос 5." + question_5 + "<br>Ваш ответ: " + answ_student_5 + "<br>Вы ответили верно" + "</span><br>";
        } else {
            all_answers += "<br><span id='nvo'>Вопрос 5.Вы ответили не верно" + "</span><br>";
        }
        total = 5;
        procent_total = count / total * 100;
        procent_total = procent_total.toFixed();

        document.getElementById('rezult').innerHTML = "Вы набрали " + ball + " баллов из "+ total_ball + "<br>Задания выполнены верно на " + procent_total + " %. " +"</span > <br><div class='progress'><div class='progress-bar' role='progressbar' style='width: " + procent_total + "%' aria-valuenow='" + procent_total + "' aria-valuemin='0' aria-valuemax='100'></div></div><span id='ot'>" + "</span><br><br><br>" + all_answers;
    }

</script>

сами вопросы и правильные ответы на те, которые типа text, хранятся в отдельном файле в переменных, например так:
question_1 = "Вопрос 1"
правильный ответ на вопросы типа radio помечены value="1"
Ответить с цитированием
  #2 (permalink)  
Старый 05.05.2020, 01:32
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068

RIMINI,
создайте массив вопросов и ответов, от него и пляшите.
https://javascript.ru/forum/misc/762...tml#post500647
потом можно перемешать массив перед выводом.
Ответить с цитированием
  #3 (permalink)  
Старый 08.05.2020, 15:37
Кандидат Javascript-наук
Отправить личное сообщение для od0201 Посмотреть профиль Найти все сообщения от od0201
 
Регистрация: 07.05.2020
Сообщений: 108

попробуйте поменять подход
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<div class="main"></div>
</body>
</html>
<script>
  const arr=[];
  arr.push({id:1,question:'вопрос 1', level:1, correctAnswer:2, answer:['ответ 1 на 1','ответ 2 на 1','ответ 3 на 1','ответ 4 на 1']})
  arr.push({id:2,question:'вопрос 2', level:1, correctAnswer:4, answer:['ответ 1 на 2','ответ 2 на 2','ответ 3 на 2','ответ 4 на 2']})
  arr.push({id:3,question:'вопрос 3', level:1, correctAnswer:1, answer:['ответ 1 на 3','ответ 2 на 3','ответ 3 на 3','ответ 4 на 3']})
  arr.push({id:4,question:'вопрос 4', level:1, correctAnswer:3, answer:['ответ 1 на 4','ответ 2 на 4','ответ 3 на 4','ответ 4 на 4']})

  arr.sort(()=>Math.random() - 0.5)
  for(let i=0;i<2 && i<arr.length-1;i++) {
    const item=arr[i]
    const ellAnswer=`<select onchange="choice(${item.id},this.options[this.selectedIndex].value)">${item.answer
      .map((a,ii)=>`<option value="${ii}">${a}</option>`)
      .join('')}</select>`
    const allBlock=`<div id="question${item.id}">
       <div>${item.question}</div>
       <div>${ellAnswer}</div>
       <div class="correctAnswer">ответ не выбран</div>
       <div>=====================</div>
    </div>`

    const ell=document.createElement('div')
    ell.innerHTML=allBlock
    document.querySelector('div.main')
      .appendChild(ell)
  }
  function choice(id,n) {
    document.querySelector(`div#question${id} div.correctAnswer`).textContent=`на вопрос ${id} получен ответ ${n}`
// здесь нам известно id вопроса и n ответа, ищем в массиве элемент вопрос и сравниваем n с correctAnswer
//https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/find
  }
</script>

Последний раз редактировалось od0201, 08.05.2020 в 15:58.
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Количество вопросов в тесте Alexmor Общие вопросы Javascript 1 09.12.2016 08:42
При запуске теста вопросы в произвольеном порядке Dr.Maksss Элементы интерфейса 13 30.09.2015 21:53
Необходимо оценить качество вопросов в тесте на знание Java8 testd Ваши сайты и скрипты 0 10.04.2015 18:31
Динамическая загрузка вопросов для теста Dimaz Элементы интерфейса 13 14.11.2012 20:01
Передача переменной в функцию для теста со случайным выводом вопросов rockdancer Общие вопросы Javascript 1 06.02.2010 23:13