Таймер обратного отсчета в секундах с перезагрузкой
Есть такой код: https://codepen.io/zikwal/pen/NWGodpV (Для воспроизведения)
UPDATE: Ответ ниже - как видно - работает и выполняет именно то, что нужно, но он написан не по моему коду - и не получается его к моему адаптировать. (Если, кто может в этом помочь - буду благодарен)
ВОПРОС:
HTML Выводится из БД через PHP, для примера запечатал HTML.
Суть в том, что при нажатии на чекбокс - меняется вопрос. Необходимо ограничить время ответа и в случае отсутствия ответа через 15 сек - сделать выбор за пользователя.
Реализовал таймер обратного отсчета но не могу реализовать к нему оставшиеся две функции:
1 - Чтобы при достижении 0 автоматически выбирался 2 ответ
2 - Чтобы при нажатии на чекбокс - таймер перезагружался
(Перекопал много постов, пытался через if else, addClass/removeClass - но реализовать так и не смог - надеюсь на помощь и хоть небольшое разъяснение)
Развёрнутый код:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test-data">
<div class="question" data-id="6" id="question-6">
<p class="q">Вопрос 1</p>
<p class="a">
<input type="radio" id="answer-1" name="question-6" value="1">
<label for="answer-1">1</label>
</p>
<p class="a">
<input type="radio" id="answer-2" name="question-6" value="2">
<label for="answer-2">2</label>
</p>
<div class="sec seconds">15</div>
</div>
<div class="question" data-id="4" id="question-4">
<p class="q">Вопрос 2</p>
<p class="a">
<input type="radio" id="answer-1" name="question-4" value="1">
<label for="answer-1">1</label>
</p>
<p class="a">
<input type="radio" id="answer-2" name="question-4" value="2">
<label for="answer-2">2</label>
</p>
<div class="sec">15</div>
</div>
<div class="question" data-id="5" id="question-5">
<p class="q">Вопрос 3</p>
<p class="a">
<input type="radio" id="answer-1" name="question-5" value="1">
<label for="answer-1">1</label>
</p>
<p class="a">
<input type="radio" id="answer-2" name="question-5" value="2">
<label for="answer-2">2</label>
</p>
<div class="sec">15</div>
</div>
</div>
CSS
.q{
border-bottom: 1px solid #000;
font-weight: bold;
}
.a {
padding: 5px 0;
}
.question {
display: none;
}
.nav-active {
display: none;
}
JS:
$('.test-data').children('div:first').show();
$('input[id^="answer"]').click(({currentTarget})=>{
$(currentTarget).parent().parent().hide().next().fadeIn();
console.log($(currentTarget).attr('name'), $(currentTarget).val());
});
$(document).ready(function() {
var sec = $('.seconds');
var secVal = parseInt(sec.text());
var timer = setTimeout(function tick() {
if (secVal > 0) {
sec.text(--secVal);
timer = setTimeout(tick, 1000);
}
}, 1000);
});
Ответы (1 шт):
id элементов по определению должны быть уникальными на странице...
Легче редактировать данные в JS, чем дублировать HTML. Было бы удобнее оформить это в таком виде:
var data = [
{
question: "Вопрос-1",
answers: ["Вариант-1", "Вариант-2"],
},
{
question: "Вопрос-2",
answers: ["100500", "500100"],
},
{
question: "Вопрос-3",
answers: ["bubu", "moo", "doo"],
},
];
/***/
var $test = $('.test-data');
var timerFrom = 15;
var index = -1;
var timeout = null;
nextQuestion();
$test.on('change', 'input[type="radio"]', function() {
logAnswer( $(this) );
nextQuestion();
});
/***/
function setHTML(index) {
var obj = data[index];
var html = '<p class="question">' + obj.question + '</p>';
for( var i = 0; i < obj.answers.length; i++ ) {
html += (
'<p class="answer">' +
'<label><input type="radio" name="question" value="' + i + '"><span>' +
obj.answers[i] +
'</span></label>' +
'</p>'
);
}
html += '<div class="sec">' + timerFrom + '</div>';
$test.html( html );
}
function nextQuestion() {
clearTimeout(timeout);
$test.fadeOut(500);
setTimeout(function() {
index++;
if( !data[index] ) return console.log("Вопросы закончились");
setHTML(index);
runTimer();
$test.fadeIn();
}, 500);
}
function runTimer() {
var sec = $('.test-data .sec');
var seconds = timerFrom;
loop();
function loop() {
sec.text( seconds );
if( seconds <= 0 ) {
autoAnswer();
nextQuestion();
return;
}
seconds--;
timeout = setTimeout(loop, 1000);
}
}
function autoAnswer() {
var answers = data[index].answers;
var $radio = $('.test-data .answer input').eq( answers.length - 1 );
$radio.prop("checked", true);
logAnswer( $radio );
}
function logAnswer($elem) {
console.log( "Номер: " + $elem.val() + ", Значение: " + $elem.next('span').text() );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test-data"></div>