I am designing a website such that a question appears on each page and users can go through the questions by clicking on the "Next" button at the bottom of every page and proceed to the next page. I want to add a back button as well so that they can go the previous pages and change their answers whenever needed.
This is the HTML code for the "Next" button:
<button ng-disabled="question.answer === undefined || question.answer == '' || question.answer == {}" ng-click="RC.nextQuestion()" type="button" class="btn btn-default" style="float:right ; margin-top:20px">Next</button>
This is the JavaScript code for the "Next" button:
this.next = function(){
if(self.state == "workerIdSlide"){
if(self.questionId == null && self.partId == null){
self.load(function(){
self.state = self.allStates[++self.slideIndex];
});
return;
}
}
if(self.slideIndex + 1 < self.allStates.length){
self.state = self.allStates[++self.slideIndex];
}else{
self.submitResults(self.resultsSubmitted, self.handleError);
}
};
This is what I tried as for the JavaScript code:
this.previous = function(){
if(self.state == "workerIdSlide"){
if(self.questionId == null && self.partId == null){
self.load(function(){
self.state = self.allStates[--self.slideIndex];
});
return;
}
}
};
this.previousQuestion = function(){
if(self.questionIndex == 0{
++self.questionIndex;
else{
self.previous();
}
};
But, it did not work. Can someone tell me how I can add a "Back" button?
Add:
this.previousQuestion = function(){
if(self.questionIndex != 0){
--self.questionIndex;
}else{
if(self.questionIndex + 1 >= self.questions.length){
self.next();
}
}
};
Remove:
this.previous = function(){
if(self.state == "workerIdSlide"){
if(self.questionId == null && self.partId == null){
self.load(function(){
self.state = self.allStates[--self.slideIndex];
});
return;
}
}
};
The complete code:
this.next = function(){
if(self.state == "workerIdSlide"){
if(self.questionId == null && self.partId == null){
self.load(function(){
self.state = self.allStates[++self.slideIndex];
});
return;
}
}
if(self.slideIndex + 1 < self.allStates.length){
self.state = self.allStates[++self.slideIndex];
}else{
self.submitResults(self.resultsSubmitted, self.handleError);
}
};
this.nextQuestion = function(){
if(self.questionIndex + 1 < self.questions.length){
++self.questionIndex;
}else{
self.next();
}
};
this.previousQuestion = function(){
if(self.questionIndex != 0){
--self.questionIndex;
}else{
if(self.questionIndex + 1 >= self.questions.length){
self.next();
}
}
};
Related
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 have made a solar system simulation and have some 'settings' which the user can change. I have made it so the settings only update when the save button is pressed. This works and the bodies are hidden if a box is checked but say for example, i checked mercury and saved the changes then wanted to check Venus as well when i save the changes Venus is hidden but Mercury is shown again. how can i make it so that Mercury stays hidden until the box in uncheked.
(note the check boxes decide whether a planet should be hidden or not so hideMer for example when true would stop drawing mercury onto the canvas)
code which i think the issue applies to:
function animate() {
//clears canvas each new loop
if (showPath==false){
c.clearRect(-innerWidth/2,-innerHeight/2,innerWidth,innerHeight);
}
hideBodies = [hideMer, hideVen, hideEar, hideMar, hideJup, hideSat, hideUra, hideNep];
drawSun();
for (var i=0; i< xPosList.length; i++){
leapfrog(i);
if (hideBodies[i]==false){
drawBody(i);
}
}
}
function saveChanges() {
showPath=(document.getElementById("showPath").value=="True");
//Mercury
if (document.getElementById("mer").checked && hideMer == false){
hideMer = true;
} else if (document.getElementById("mer").checked && hideMer == true){
hideMer = false;
}
//Venus
if (document.getElementById("ven").checked && hideVen == false){
hideVen = true;
} else if (document.getElementById("ven").checked && hideVen == true){
hideVen = false;
}
//Earth
if (document.getElementById("ear").checked && hideEar == false){
hideEar = true;
} else if (document.getElementById("ear").checked && hideEar == true){
hideEar = false;
}
//Mars
if (document.getElementById("mar").checked && hideMar == false){
hideMar = true;
} else if (document.getElementById("mar").checked && hideMar == true){
hideMar = false;
}
//Jupiter
if (document.getElementById("jup").checked && hideJup == false){
hideJup = true;
} else if (document.getElementById("jup").checked && hideJup == true){
hideJup = false;
}
//Saturn
if (document.getElementById("sat").checked && hideSat == false){
hideSat = true;
} else if (document.getElementById("sat").checked && hideSat == true){
hideSat = false;
}
//Uranus
if (document.getElementById("ura").checked && hideUra == false){
hideUra = true;
} else if (document.getElementById("ura").checked && hideUra == true){
hideUra = false;
}
//Neptune
if (document.getElementById("nep").checked && hideNep == false){
hideNep = true;
} else if (document.getElementById("nep").checked && hideNep == true){
hideNep = false;
}
console.log(hideMer);
alert(hideMer);
}
whole code: https://jsfiddle.net/nczpod06/6/
In the function save changes for each planet I'm only changing the boolean value when it is checked and not when it is unchecked. To fix this (for example for mercury) I needed to add the not boolean logical operator and then it works... for example:
//Mercury
if (document.getElementById("mer").checked && hideMer == false){
hideMer = true;
} else if (!(document.getElementById("mer").checked) && hideMer == true){
hideMer = false;
}
I have some problem when I check the function validation, I need when checking all the cassis is true hide the parent div * errors message *
var error_pass = false;
$('#pass').focusout(function(){
check_pass();
error_pass = false;
if(error_pass !== true){
console.log('its showing!');
}else{
$('.test').fadeOut('522');
}
});
function check_pass() {
var fpass= $('#pass').val();
switch(error_pass = true){
case(fpass.length < 6 ? $('#pass-error-message3').css('color','red'):$('#pass-error-message3').css('color','green') ):
$('#pass-error-message3').show();
case(fpass.search(/(?=.[a-z])(?=.*[A-Z])/) == -1 ? $('#pass-error-message4').css('color','red') : $('#pass-error-message4').css('color','green')):
$('#pass-error-message4').show();
case(fpass.search(/\d/) == -1 ? $('#pass-error-message2').css('color','red'):$('#pass-error-message2').css('color','green')):
$('#pass-error-message2').show();
default:break;
}
}
Use if else statements like this
function validation() {
var error = false;
if (fpass.length < 6) {
error = true;
$('#pass-error-message3').css('color', 'red').show();
} else {
$('#pass-error-message3').css('color', 'green');
}
if (fpass.search(/(?=.[a-z])(?=.*[A-Z])/) == -1) {
error = true;
$('#pass-error-message4').css('color', 'red').show();
} else {
$('#pass-error-message4').css('color', 'green')
}
if(fpass.search(/\d/) == -1){
error = true;
$('#pass-error-message2').css('color','red').show();
}else{
$('#pass-error-message2').css('color','green');
}
if(error === false){
hideParentDiv(); // Here hide the div
}
}
Much cleaner approach
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++) {
//
}
I am looking to make a checkbox that when unchecked, will turn off a certain function in a .js file. Can someone help me?
popup.html
HTML Check box:
content.js
Turn off this function:
var tweet = new Array();
var tweetName = new Array();
function linkSnipe() {
for (var i = 0; i < 5; i++) {
tweetName[i] = document.getElementsByClassName("fullname js-action-profile-name show-popup-with-id")[0].innerHTML;
tweet[i] = document.getElementsByClassName("js-tweet-text")[i].innerHTML;
}
if (tweet[0].match(shoeName) == shoeName && tweet[0].match(filterer) != filterer && tweet[0].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[0].click();
update();
}
}
else if (tweet[1].match(shoeName) == shoeName && tweet[1].match(filterer) != filterer && tweet[1].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[1].click();
update();
}
}
else if (tweet[2].match(shoeName) == shoeName && tweet[2].match(filterer) != filterer && tweet[2].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[2].click();
update();
}
}
else if (tweet[3].match(shoeName) == shoeName && tweet[3].match(filterer) != filterer && tweet[3].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[3].click();
update();
}
}
else if (tweet[4].match(shoeName) == shoeName && tweet[4].match(filterer) != filterer && tweet[4].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[4].click();
update();
}
}
else if(checkon == "Tweets") {
location.reload();
}
}
setTimeout("linkSnipe()", 250);
}
When the checkbox is checked, redefine the function as:
<input type=checkbox ..... onchange="doit()">
function doit() {
window.linkSnipe=function() {}
}
I've used this too:
function doit() {
window['linkSnipe']=function() {}
}
If you want to turn the function on and off by the checkbox:
<input type=checkbox ..... onchange="doit(this)">
var linkSnipeSave = linkSnipe;
function doit(ck) {
if (ck.checked)
window['linkSnipe']=linkSnipeSave
else {
linkSnipeSave = linkSnipe; //not sure if this line is needed...pls test
window['linkSnipe']=function() {}
}
}
You could simply have a Boolean variable that changes with the state of your check box. You could then put an if statement around the function call that will only trigger if the checkbox is checked.
http://jsfiddle.net/W5P8X/
//initialize some variables.
bike_checked = false;
car_checked = false;
//get elements by their ID from html
bike = document.getElementById("bike");
car = document.getElementById("car");
//add event listeners to the html elements we found above
bike.addEventListener("click", toggle_bike, false);
car.addEventListener("click", toggle_car, false);
//toggle bike_checked variable on click
function toggle_bike(){
if(bike_checked == true)
bike_checked = false;
else
bike_checked=true;
current_state();
}
//toggle car_checked variable on click
function toggle_car(){
if(car_checked == true)
car_checked = false;
else
car_checked=true;
current_state();
}
//output current state.
function current_state(){
if(car_checked == true)
alert('Car checked');
if(bike_checked == true)
alert('Bike checked');
}
I answered with only javascript and no jQuery, but you could probably make it a bit more concise with jQuery.
I hope this helps.