I built a trivia game and if you run out of time then the function score() I wrote runs grades your game. This function is also tied to the submit button. So the issue arises when you finish the quiz with time remaining; because once you submit your score if the time goes to zero before you click try again it doubles your score.
How can get around this issue; I'm open to fixing it in the timer function or writing another function to prevent it from grading twice.
side note the try again button can't reset the page per requirements so I have the start button begin the countdown() (timer).
So the function I need is to check if score has been run and if it has don't run it again ; then the count has to reset when you click the start button.
var button = document.getElementById("main-button")
var taButton = document.getElementById("ta-button")
var quizText = document.getElementById("quiz")
var correct = 0;
var incorrect = 0;
var notAnswered = 0;
var correctText = document.getElementById("correct-text")
var incorrectText = document.getElementById("incorrect-text")
var notAnsweredText = document.getElementById("notAnswered-text")
var timeLeft = 70;
var timeLeftText = document.getElementById("timeLeft-text")
var elem = document.getElementById('some_div');
var timerId = setInterval(countdown, 1000);
// timer function
function countdown() {
if (timeLeft == 0) {
clearTimeout(timerId);
score();
} else {
timeLeftText.textContent = "Time Remaining " + timeLeft;
timeLeft--;
}
function start() {
document.getElementById("main-button").style.display = "none";
document.getElementById("quiz").style.display = "block";
document.getElementById("some_div").style.display = "inline-block";
timeLeft = 70;
countdown();
timeLeftText.textContent = "Time Remaining " + timeLeft;
}
function score() {
correct = 0;
incorrect = 0;
notAnswered = 0;
var question1
var question2
var question3
var question4
var question5
var question6
var question7
var question8
var question9
var question10
// checks if the value of or radio is null.
if (document.querySelector('input[name="question1"]:checked') === null) { notAnswered++;
}
// if it has a value it logs the value
// then takes the value that was stored to the radio button and clears it; resetting or buttons.
else { question1 = document.querySelector('input[name="question1"]:checked').value;
document.querySelector('input[name="question1"]').checked=false;
// This checks the value we stored and then determines if it that value is the correct answer.
if (question1 === "d") {
correct++;
}
else if ((question1 === "a") || (question1 === "b") || (question1 === "c")) {
incorrect++;
}}
// question 2.
if (document.querySelector('input[name="question2"]:checked') === null) { notAnswered++;
}
else { question2 = document.querySelector('input[name="question2"]:checked').value;
document.querySelector('input[name="question2"]').checked=false;
if (question2 === "d") {
correct++;
}
else if (question2 === "a" || "b" || "c") {
incorrect++;
}}
// question 3.
if (document.querySelector('input[name="question3"]:checked') === null) { notAnswered++;
}
else { question3 = document.querySelector('input[name="question3"]:checked').value;
document.querySelector('input[name="question3"]').checked=false;
if (question3 === "a") {
correct++;
}
else if (question2 === "b" || "c" || "d") {
incorrect++;
}}
// question 4
if (document.querySelector('input[name="question4"]:checked') === null) { notAnswered++;
}
else { question4 = document.querySelector('input[name="question4"]:checked').value;
document.querySelector('input[name="question4"]').checked=false;
if (question4 === "d") {
correct++;
}
else if (question4 === "a" || "b" || "c") {
incorrect++;
}}
// question 5
if (document.querySelector('input[name="question5"]:checked') === null) { notAnswered++;
}
else { question5 = document.querySelector('input[name="question5"]:checked').value;
document.querySelector('input[name="question5"]').checked=false;
if (question5 === "d") {
correct++;
}
else if (question5 === "a" || "b" || "c") {
incorrect++;
}}
// question 6
if (document.querySelector('input[name="question6"]:checked') === null) { notAnswered++;
}
else { question6 = document.querySelector('input[name="question6"]:checked').value;
document.querySelector('input[name="question6"]').checked=false;
if (question6 === "c") {
correct++;
}
else if (question6 === "a" || "b" || "c") {
incorrect++;
}}
// question 7
if (document.querySelector('input[name="question7"]:checked') === null) { notAnswered++;
}
else { question7 = document.querySelector('input[name="question7"]:checked').value;
document.querySelector('input[name="question7"]').checked=false;
if (question7 === "a") {
correct++;
}
else if (question7 === "a" || "b" || "c") {
incorrect++;
}}
// question 8
if (document.querySelector('input[name="question8"]:checked') === null) { notAnswered++;
}
else { question8 = document.querySelector('input[name="question8"]:checked').value;
document.querySelector('input[name="question8"]').checked=false;
if (question8 === "b") {
correct++;
}
else if (question8 === "a" || "b" || "c") {
incorrect++;
}}
// question 9
if (document.querySelector('input[name="question9"]:checked') === null) { notAnswered++;
}
else { question9 = document.querySelector('input[name="question9"]:checked').value;
document.querySelector('input[name="question9"]').checked=false;
if (question9 === "c") {
correct++;
}
else if (question9 === "a" || "b" || "c") {
incorrect++;
}}
// question10
if (document.querySelector('input[name="question10"]:checked') === null) { notAnswered++;
}
else { question10 = document.querySelector('input[name="question10"]:checked').value;
document.querySelector('input[name="question10"]').checked=false;
if (question10 === "c") {
correct++;
}
else if (question10 === "a" || "b" || "c") {
incorrect++;
}}
// this toggles what is visible on their screen.
document.getElementById("quiz").style.display = "none";
document.getElementById("scoreBox").style.display = "block";
document.getElementById("some_div").style.display = "none";
document.getElementById("ta-button").style.display = "inline-block";
// this is the text for our score box
correctText.textContent = "Correct " + correct;
incorrectText.textContent = "Incorrect " + incorrect;
notAnsweredText.textContent = "Not Answered " + notAnswered;
}
function reset() {
// this toggles what is visible on their screen.
document.getElementById("quiz").style.display = "none";
document.getElementById("some_div").style.display = "none";
document.getElementById("ta-button").style.display = "none";
document.getElementById("scoreBox").style.display = "none";
document.getElementById("main-button").style.display = "block";
// this resets the score
correct = 0;
incorrect = 0;
notAnswered = 0;
// allows the start button to be clicked up to 20 mins after the ta button, so that the score function does start before the game.
timeLeft = 12000;
}
<div id="button-container">
<div id="ta-button">
<p id="main-button"><button type="button" class=" btn-lg btn-block text-light "
onclick="reset()"><i class="fas fa-sync"></i> Try Again? <i class="fas fa-sync"></i></button></p>
</div>
</div>
<div id="button-content" class="container">
<p id="main-button"><button type="button" class=" btn-lg btn-block text-light "
onclick="start();countdown()"><i class="fas fa-user-astronaut"></i> Start
Quiz. <i class="fas fa-user-astronaut"></i></button></p>
</div>
Try this.
var timerId = null;
var timeLeft = 70;
function countDown() {
if (timerId) {
clearTimeout(timerId);
}
//do what ever
if (timeLeft < 1) {
//do something else
//then return
return 0;
}
else {
timerId = setTimeout(countDown, 1000);
}
}
function start() {
//do whatever
timerId = setTimeout(countDown, 1000);
}
If you need more info on timers in javascript check out https://www.w3schools.com/jsref/met_win_settimeout.asp
I'm trying to get the quiz to loop 5 times while recording the correct answer for each question before returning to start menu but I'm struggling to get it working
Any help with this will be much appreciated.
function cleartxt()
{
setTimeout("document.getElementById('ans').innerHTML = ''", 3000);
}
var random = new Array(5);
var count = 0;
function next()
{
var store = 0;
do
{
store = (Math.round(Math.ceil(Math.random() * 40) -1));
}while(random.indexOf(store) > -1);
document.getElementById("ques").innerHTML = questions[store][0];
document.getElementById("rad1").innerHTML = questions[store][1];
document.getElementById("rad2").innerHTML = questions[store][2];
document.getElementById("rad3").innerHTML = questions[store][3];
document.getElementById("rad4").innerHTML = questions[store][4];
document.getElementById("image").src = images[store];
var radio = document.getElementsByName("rad");
while(store <= 5)
{
count++;
if(store == 5)
startMenu();
if(radio[0].checked == true)
{
if(questions[store][0] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[1].checked == true)
{
if(questions[store][1] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[2].checked == true)
{
if(questions[store][2] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[3].checked == true)
{
if(questions[store][3] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else
document.getElementById("ans").innerHTML = "Please select an answer!";
}
}
function startMenu()
{
window.history.back();
}
I am trying like this:
function k(){
var x = $('#textArea').val();
for (i = 0; i < x.length; i++)
{
if(x[i].match(/^[0-9]/))
{
if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[-]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[-]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/) && x[i+9].match(/^[0-9]/) && x[i+10].match(/^[0-9]/))
{
if(x[i+11].match(/^[0-9]/))
{
return 'true';
}
else
{
return false;
}
}
else if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[0-9]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[0-9]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/))
{
if(x[i+9].match(/^[0-9]/))
{
return 'true';
}
else
{
return false;
}
}
else
{
continue;
}
}
else
{
continue;
}
}
return 'true';
}
Or simply
var x = $('#textArea').val();
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
return true;
}
return false;
Or if you only want to allow - and digits
var x = $('#textArea').val();
var matches = x.match( /[0-9-]/g ).length;
if ( !matches || matches.length != x.length )
{
return false;
}
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
return true;
}
return false;
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">
or using pure regexp
to match the 123-45-678 and 12345678 formats:
var x = $('#textArea').val();
if (x.match(/^\d{3}-\d{2}-\d{3}$|^\d{8}$/) {
return true;
} else return false;
to match any number less then 9 digits:
var x = $('#textArea').val();
if (x.match(/^(?:\d-?){1,8}$/) {
return true;
} else return false;
I have an extremely complex page that uses dynamic information to generate a layout with the correct and relevant information.
I am storing the data as an object. I have essentially 15 objects with multiple fields of user-submitted data.
Everything is stored and output correctly on the page, however now I am trying to validate and the information when the user tries to edit it from the edit page. The information is all being generated and laid out correctly, however I keep getting the same errors on the validation of the information.
The validation should go through and determine if a field was filled out correctly, and if it was not record a variable and add it to an alert variable. Then once it i done running the validation function it should pop up an alert with what fields still need to be filled in.
I keep receiving an error when it runs through the for loop toward the bottom. It says 'Uncaught TypeError' Cannot read property 'questionNumber' of undefined.
Above the code below I store the object and the properties, but this function is where everything is going awry. Note that there are also 15 arrays in the qtest object, but for the sake of simplification I removed all but a few.
I have gotten this to work on smaller, simpler forms, however because of the complexity and storage method I think this may be missing something or I might not be accessing something correctly. The code is very long and below, I've scaled back as much as possible. Please, if you have any insight or help you can provide I would be extremely grateful. Thank you!
var validateQ = function(qTextID, qAnswerType, TFID, MCID, MCText1, MCText2, MCText3, MCText4, VisRef, Youtube, Vimeo, ImgID) {
if (document.getElementById('ItemName').value == "") {
var quizName = true;
};
if (jQuery('select[name="CAT_Custom_14"]').val() == 'Quiz') {
if (jQuery(qTextID).val() == "") {
var qText = true;
};
if (jQuery('CAT_Custom_249').val() == " ") {
var quizscore1 = true;
};
if (jQuery(qAnswerType).val() == " ") {
var answertype = true;
} else if (jQuery(qAnswerType).val() == 'True/False') {
if (!jQuery(TFID).is(':checked')) {
var tfanswer = true;
var mcanswer = false;
};
} else if (jQuery(qAnswerType).val() == 'Multiple Choice') {
if (!jQuery(MCID).is(':checked')) {
var mcanswer = true;
var tfanswer = false;
};
if (jQuery(MCText1).val() == "" || jQuery(MCText2).val() == "" || jQuery(MCText3).val() == "" || jQuery(MCText4).val() == "") {
var mcTextfields = true;
} else {
mcTextfields = false;
};
};
} else if (jQuery('select[name="CAT_Custom_14"]').val() == 'Survey') {
if (jQuery(qTextID).val() == "") {
var qText = true;
};
if (!jQuery(sAnswers1).is(':checked')) {
var surveyAnswers1 = true;
} else {
surveyAnswers1 = false;
};
};
if (jQuery(VisRef).val() != " ") {
if (jQuery(VisRef).val() == "Youtube Video" && jQuery(Youtube).val() == "") {
var youtubeVal = true;
} else if (jQuery(VisRef).val() == "Vimeo Video" && jQuery(Vimeo).val() == "") {
var vimeoVal = true;
} else {
// validateImage(ImgID);
};
} else {
youtubeVal = false;
vimeoVal = false;
var tempImgCheck = false;
};
if (numCheck == 15) {
numCheck = 16;
};
var qName = "- Quiz or Survey Name\n";
var shortDescription = "- A short description of the Quiz/Survey\n";
var scoreMessage = "- A required passing score\n";
var QTextMessage = "- Question text\n";
var answerTMessage = "- An answer type\n";
var mcFields = "- The Multiple Choice answer fields\n";
var mcMessage = "- The correct Multiple Choice Answer\n"
var tfMessage = "- The correct True/False answer\n";
var vimMessage = "- A Vimeo Video code\n";
var ytMessage = "- A Youtube Video code\n";
var imgMessage = "- A reference image\n";
var surveyMessage = "- An answer type\n";
if (quizName == true || quizscore1 == true || qText == true || answertype == true || tfanswer == true || mcanswer == true || mcTextfields == true || youtubeVal == true || vimeoVal == true || tempImgCheck == true || surveyAnswers1 == true) {
var alertText = "It appears that you have not finished completing question" + question[i].questionNumber + ". Please ensure that you have completed the following question fields.\n";
if (quizName == true) {
alertText = alertText + qName;
};
if (quizscore1 == true) {
alertText = alertText + scoreMessage;
};
if (qText == true) {
alertText = alertText + QTextMessage;
};
if (answertype == true) {
alertText = alertText + answerTMessage;
};
if (tfanswer == true) {
alertText = alertText + tfMessage;
};
if (mcanswer == true) {
alertText = alertText + mcMessage;
};
if (mcTextfields == true) {
alertText = alertText + mcFields;
};
if (youtubeVal == true) {
alertText = alertText + ytMessage;
};
if (vimeoVal == true) {
alertText = alertText + vimMessage;
};
if (tempImgCheck == true) {
alertText = alertText + imgMessage;
};
if (surveyAnswers1 == true) {
alertText = alertText + surveyMessage;
};
if (quizscore1 == true) {
alertText = alertText + scoreMessage;
};
confirm(alertText);
};
};
var numCheck = 1;
var checkQuizQ = function() {
for (j = 1; j<= qtest.length; j++) {
numCheck = numCheck + 1;
if (qtest[j].questionNumber == "1") {
validateQ("CAT_Custom_3", "CAT_Custom_8", "CAT_Custom_19", "CAT_Custom_18", "CAT_Custom_4", "CAT_Custom_5", "CAT_Custom_6", "CAT_Custom_7", "CAT_Custom_9", "CAT_Custom_10", "CAT_Custom_11", "CAT_Custom_12", "CAT_Custom_230");
} else if (qtest[j].questionNumber == "2") {
validateQ("CAT_Custom_20", "CAT_Custom_21", "CAT_Custom_29", "CAT_Custom_26", "CAT_Custom_22", "CAT_Custom_23", "CAT_Custom_24", "CAT_Custom_25", "CAT_Custom_30", "CAT_Custom_31", "CAT_Custom_32", "CAT_Custom_33", "CAT_Custom_231");
} else if (qtest[j].questionNumber == "3") {
validateQ("CAT_Custom_35", "CAT_Custom_36", "CAT_Custom_37", "CAT_Custom_40", "CAT_Custom_41", "CAT_Custom_42", "CAT_Custom_43", "CAT_Custom_44", "CAT_Custom_45", "CAT_Custom_46", "CAT_Custom_47", "CAT_Custom_48", "CAT_Custom_232");
} else if (qtest[j].questionNumber == "4") {
};
};
document.getElementById('catcustomcontentbutton').style.display = "block";
document.getElementById("qsValidate").style.display = "none";
};
Since qtest looks like an array, its index starts from 0 to length - 1 so when j is length the value of qtest[j] will be undefined.
So change the loop as
for (j = 0; j< qtest.length; j++) {
//
}
Below is my code. It is supposed to filter a table. It functions great in everything but IE. Can you help?
Perhaps there is a missing tag or something. I've been over it a number of times and could really do with someone's help please!
<script type="text/javascript">
function hasPath(element, cls) {
return (' ' + element.getAttribute('pathway')).indexOf(cls) > -1;
}
function hasLevel(element, cls) {
return (' ' + element.getAttribute('level')).indexOf(cls) > -1;
}
function hasBody(element, cls) {
return (' ' + element.getAttribute('body')).indexOf(cls) > -1;
}
function QualificationSearch() {
var imgdiv = document.getElementById("Chosen_Pathway_img");
var p = document.getElementById("PathwaySelect");
var pathway = p.options[p.selectedIndex].value;
if (pathway == "ALLPATHS") {
pathway = "";
imgdiv.src = "/templates/superb/images/QualChecker/pic_0.png"
}
if (pathway == "ES") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_1.png"
}
if (pathway == "HOUSING") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_2.png"
}
if (pathway == "PLAYWORK") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_3.png"
}
if (pathway == "SC") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_4.png"
}
if (pathway == "YW") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_5.png"
}
var a = document.getElementById("AwardingBodySelect");
var awardingBody = a.options[a.selectedIndex].value;
if (awardingBody == "ALLBODIES") {
awardingBody = "";
}
var levelGroup = document.getElementsByName("LevelGroup");
var chosenLevel = ""
for (var g = 0; g < levelGroup.length; g++) {
if (levelGroup[g].checked) {
chosenLevel += levelGroup[g].value + " ";
}
}
if (chosenLevel == undefined) {
var chosenLevel = "";
} else {
var splitLevel = chosenLevel.split(" ");
var levelA = splitLevel[0];
var levelB = splitLevel[1];
var levelC = splitLevel[2];
var levelD = splitLevel[3];
if (levelA == "") {
levelA = "NOLVL"
}
if (levelB == "") {
levelB = "NOLVL"
}
if (levelC == "") {
levelC = "NOLVL"
}
if (levelD == "") {
levelD = "NOLVL"
}
}
var fil = document.getElementsByName("QList");
for (var i = 0; i < fil.length; i++) {
fil.item(i).style.display = "none";
if ((hasBody(fil.item(i), awardingBody) == true || awardingBody == "") && (hasPath(fil.item(i), pathway) == true || pathway == "") && ((hasLevel(fil.item(i), levelA) == true || hasLevel(fil.item(i), levelB) == true || hasLevel(fil.item(i), levelC) == true || hasLevel(fil.item(i), levelD) == true) || chosenLevel == "")) {
fil.item(i).style.display = "block";
}
}
}
</script>
Check your semicolons. IE is far more strict on that kind of stuff than FF.