Problem in executing the complete javascript - javascript

The program is not running and just showing blank window when opened in browser. Please help me found the issue with the code why it is not executing You need to create a program that will display flight information to a person. The program will continue to provide
information to the user until they indicate that they are no longer interested in searching (they will enter Q or X to stop).
The user will be prompted to enter a city to search for and you will look for any flight that starts in this city and display
the information associated with that flight.
//declare the arrays
startCity = ["Atlanta", " Cleveland", " Indianapolis", "Louisville"];
endcity = ["Cleveland", "Indianapolis", "Louisville ", "Atlanta"];
flightNumber = [RE103, RE305, RE307, RE309];
pricePerPerson = [110, 75, 90, 120];
//window onload method
window.onload = (function() {
//call function to prompt user
processPromtExecution();
//prmpt user to ask input
function processPromtExecution() {
//ask user to privide imput
var inputString = prompt("Looking for a flight? Enter the title or X to quit", "");
//check user input and if inpt is Q/q/X/x the quti with message
if (inputString == "Q" || inputString == "X" || inputString == "x" || inputString == "q") {
$("#idSpan").append("<hr /> <br />");
$("#idSpan").append("Thank you for using our flights system.");
} else {
//else search the input
for (var i = 0; i < startCity.length; i++) {
//chck input strin is part of array of book titles element or not
if (startCity[i].toLowerCase().indexOf(inputString.toLowerCase()) >= 0) {
//if matches then fetch index of other arrays
var startCity = startCity[i];
var endCity = endCity[i];
var flightNumber = flightNumber[i];
var pricePerPerson = pricePerPerson[i];
//print the message below
document.getElementById("idSpan").style.display = "block";
$("#idSpan").append("<hr />");
//set the values
$("#idSpan").append("flight Information: <br />");
$("#idSpan").append("starta: " + startCity + "<br />");
$("#idSpan").append("endCity: " + endCity + "<br />");
$("#idSpan").append("Number: " + flightNumber + "<br />");
$("#idSpan").append("Cost: " + pricePerPerson + "<br />");
//ask again
processPromtExecution();
}
}
}
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<span id="idSpan" style="display:none;">Welcome to the Javascript flightS</span>
</body>
</html>

Looks like you forgot the quote in your array with string and numbers combined in the following line:
flightNumber = [RE103, RE305, RE307, RE309];
Shouldn't it look like this:
flightNumber = ["RE103", "RE305", "RE307", "RE309"];

Consider the following.
/*
//declare the arrays
startCity = ["Atlanta", " Cleveland", " Indianapolis", "Louisville"];
endcity = ["Cleveland", "Indianapolis", "Louisville ", "Atlanta"];
flightNumber = ["RE103", "RE305", "RE307", "RE309"];
pricePerPerson = [110, 75, 90, 120];
*/
// Prepare data
var flights = [{
flightNumber: "RE103",
city: {
start: "Atlanta",
finish: "Cleveland"
},
pricePerPerson: 110
}, {
flightNumber: "RE305",
city: {
start: "Cleveland",
finish: "Indianapolis"
},
pricePerPerson: 75
}, {
flightNumber: "RE307",
city: {
start: "Indianapolis",
finish: "Louisville"
},
pricePerPerson: 90
}, {
flightNumber: "RE309",
city: {
start: "Louisville",
finish: "Atlanta"
},
pricePerPerson: 120
}];
$(function() {
// Define Functions
function getFlightDataByNumber(flightNumber, flightData) {
var results = false;
$.each(flightData, function(index, flight) {
if (flight.flightNumber.toLowerCase() == flightNumber.toLowerCase()) {
results = flight;
}
});
return results;
}
function getFlightDataByStart(cityName, flightData) {
var results = false;
$.each(flightData, function(index, flight) {
if (flight.city.start.toLowerCase() == cityName.toLowerCase()) {
results = flight;
}
});
return results;
}
function promptForFlight() {
var inputString = prompt("Looking for a flight? Enter the title or X to quit", "");
if (inputString == "Q" || inputString == "X" || inputString == "x" || inputString == "q") {
$("#idSpan").append("<hr /> <br />");
$("#idSpan").append("Thank you for using our flights system.");
} else {
var myFlight = getFlightDataByStart(inputString, flights);
if (myFlight !== false) {
$("#idSpan").show();
$("<ul>", {
class: "flightData"
}).insertAfter("#idSpan");
$("<li>").html("<label>Flight Information:</label>").appendTo(".flightData");
$("<li>").html("<label class='fixed'>Departs:</label>" + myFlight.city.start).appendTo(".flightData");
$("<li>").html("<label class='fixed'>Arrives:</label>" + myFlight.city.finish).appendTo(".flightData");
$("<li>").html("<label class='fixed'>Number:</label>" + myFlight.flightNumber).appendTo(".flightData");
$("<li>").html("<label class='fixed'>Cost:</label>$" + myFlight.pricePerPerson.toFixed(2)).appendTo(".flightData");
}
}
}
// Run Code
promptForFlight();
});
/*
//window onload method
window.onload = (function() {
//call function to prompt user
processPromtExecution();
//prmpt user to ask input
function processPromtExecution() {
//ask user to privide imput
var inputString = prompt("Looking for a flight? Enter the title or X to quit", "");
//check user input and if inpt is Q/q/X/x the quti with message
if (inputString == "Q" || inputString == "X" || inputString == "x" || inputString == "q") {
$("#idSpan").append("<hr /> <br />");
$("#idSpan").append("Thank you for using our flights system.");
} else {
//else search the input
for (var i = 0; i < startCity.length; i++) {
//chck input strin is part of array of book titles element or not
if (startCity[i].toLowerCase().indexOf(inputString.toLowerCase()) >= 0) {
//if matches then fetch index of other arrays
var startCity = startCity[i];
var endCity = endCity[i];
var flightNumber = flightNumber[i];
var pricePerPerson = pricePerPerson[i];
//print the message below
document.getElementById("idSpan").style.display = "block";
$("#idSpan").append("<hr />");
//set the values
$("#idSpan").append("flight Information: <br />");
$("#idSpan").append("starta: " + startCity + "<br />");
$("#idSpan").append("endCity: " + endCity + "<br />");
$("#idSpan").append("Number: " + flightNumber + "<br />");
$("#idSpan").append("Cost: " + pricePerPerson + "<br />");
//ask again
processPromtExecution();
}
}
}
}
});
*/
.flightData {
margin: 0;
padding: 0;
list-style: none;
}
.flightData li label {
font-weight: bold;
display: inline-block;
}
.flightData li label.fixed {
width: 120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="idSpan" style="display:none;">Welcome to the Javascript flightS</span>
Instead of using multiple unique Arrays, you may want to use an Array of Objects. This will help create a relationship between the various elements. Once you have identified the one object you need, you can easily access all the other related details.
Based on your code, you are asking the User to enter a City name, yet this is not explained well in your Prompt. You should consider clarifying the prompt better or using another Input method.
Once we have the User input, we can use the function to seek out the proper object, if we do not find it, false is returned. You have no feedback to the User if the Flight cannot be found. You might consider that scenario further.

Related

Im trying to add a button so when i click it the code (game) starts from scratch

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Hangman Test</title>
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<body>
<div class="mainDiv">
<button type="button" id="startButton">Start Game</button>
<!-- This is where the blank word will be displayed -->
<div id="city-text"></div>
<div id="wins-guesses">
<h2 id="wins-num"></h2>
<h2 id="guesses-num"></h2>
</div>
<div id="letters-guessed"></div>
</div>
<script src="assets/javascript/game.js"></script>
</body>
</html>
var secretWord = [];
var underScoreWord = [];
var wins = 0;
var guessesRemaining = 15;
var alreadyGuessed = [];
var wordLetter = false;
//Assign HTML elements to variables
var cityText = document.getElementById("city-text");
var winsNum = document.getElementById("wins-num");
var guessesNum = document.getElementById("guesses-num")
var lettersGuessed = document.getElementById("letters-guessed")
//Array of cities
var city = ["PARIS", "WELLINGTON", "HANOI", "PERTH", "MARSEILLE", "LONDON", "OTTAWA", "ZURICH", "BOSTON", "TOKYO", "DETROIT", "LIVERPOOL"];
//console.log(city);
//Pick random word from the team array and push the result to an empty array.
function pickRandomCity() {
var randomCity = city[Math.floor(Math.random() * city.length)];
secretWord = randomCity.split('');
return randomCity;
}
var cityPicked = pickRandomCity();
//Get length of secretWord and push as underscores to am empty array
for (var i = 0; i < cityPicked.length; i++) {
underScoreWord.push("_");
}
console.log('secretWord : ' + secretWord);
// console.log('underScoreWord : ' + underScoreWord);
// console.log('------------------');
// console.log('cityPicked : ' + cityPicked);
//Check for letters
//Listen for key press and check to see if its a match
var guessedLetters = {};
document.onkeyup = function letterCheck(event) {
var userGuess = event.key;
if (!guessedLetters[userGuess.toUpperCase()]) { // check if user pressed this key
alreadyGuessed.push(userGuess.toUpperCase());
guessedLetters[userGuess.toUpperCase()] = true;
guessesRemaining--;
} else { // this key has been pressed before, don't do anything
return;
}
secretWord.map((n, i) => {
if (userGuess.toUpperCase() === n.toUpperCase()) {
underScoreWord[i] = n;
}
})
console.log("Already guessed: " + alreadyGuessed);
lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
// Write to page
cityText.textContent = underScoreWord.join(" ");
winsNum.textContent = ("Wins: " + wins);
guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
console.log(underScoreWord);
// Change counter
if (guessesRemaining === 0) {
cityText.textContent = ("You lose");
}
if (secretWord.toString() === underScoreWord.toString()) {
cityText.textContent = ("You win");
wins++;
}
}
console.log(underScoreWord);
I'm trying to add a button. So, when I click it, the game starts from scratch - All numbers refresh and the hidden word is ready to be guessed. I have made it so when the full word has been guessed. It adds wins++ and if the number of guesses goes to zero the there is a message that says "You lose".
I'm trying to get it all connected so I can press the button anytime to start the game again.
How to do it?
Theres a simple solution that is to wrap everything you have in a function, and call that function when you click that button. Also disable the button when you run it, and enable it when game ends. Also clear the texts.
Another solution would be to just reset every variable and text.
var wins = 0;
function newGame(){
document.querySelector("#startButton").disabled = true;
var secretWord = [];
var underScoreWord = [];
var guessesRemaining = 15;
var alreadyGuessed = [];
var wordLetter = false;
//Assign HTML elements to variables
var cityText = document.getElementById("city-text");
var winsNum = document.getElementById("wins-num");
var guessesNum = document.getElementById("guesses-num");
var lettersGuessed = document.getElementById("letters-guessed");
lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
//Array of cities
var city = ["PARIS", "WELLINGTON", "HANOI", "PERTH", "MARSEILLE", "LONDON", "OTTAWA", "ZURICH", "BOSTON", "TOKYO", "DETROIT", "LIVERPOOL"];
//console.log(city);
//Pick random word from the team array and push the result to an empty array.
function pickRandomCity() {
var randomCity = city[Math.floor(Math.random() * city.length)];
secretWord = randomCity.split('');
return randomCity;
}
var cityPicked = pickRandomCity();
//Get length of secretWord and push as underscores to am empty array
for (var i = 0; i < cityPicked.length; i++) {
underScoreWord.push("_");
}
cityText.textContent = underScoreWord.join(" ");
console.log('secretWord : ' + secretWord);
// console.log('underScoreWord : ' + underScoreWord);
// console.log('------------------');
// console.log('cityPicked : ' + cityPicked);
//Check for letters
//Listen for key press and check to see if its a match
var guessedLetters = {};
document.onkeyup = function letterCheck(event) {
var userGuess = event.key;
if (!guessedLetters[userGuess.toUpperCase()]) { // check if user pressed this key
alreadyGuessed.push(userGuess.toUpperCase());
guessedLetters[userGuess.toUpperCase()] = true;
guessesRemaining--;
} else { // this key has been pressed before, dont do anything
return;
}
secretWord.map((n, i) => {
if (userGuess.toUpperCase() === n.toUpperCase()) {
underScoreWord[i] = n;
}
})
console.log("Already guessed: " + alreadyGuessed);
lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
// Write to page
cityText.textContent = underScoreWord.join(" ");
guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
console.log(underScoreWord);
// Change counter
if (guessesRemaining === 0) {
cityText.textContent = ("You lose");
document.querySelector("#startButton").disabled = false;
}
if (secretWord.toString() === underScoreWord.toString()) {
cityText.textContent = ("You win");
wins++;
winsNum.textContent = ("Wins: " + wins);
document.querySelector("#startButton").disabled = false;
}
}
console.log(underScoreWord);
}
newGame();
<div class="mainDiv">
<button type="button" id="startButton" onclick="newGame()">Start Game</button>
<!-- This is where the blank word will be displayed -->
<div id="city-text"></div>
<div id="wins-guesses">
<h2 id="wins-num"></h2>
<h2 id="guesses-num"></h2>
</div>
<div id="letters-guessed"></div>
</div>

Add user input to array // Javascript

This is the code I have so far. When the user enters a word into the input box, I want that word to be stored in an array via the Add Word button. Once a number of words have been entered, the user clicks the Process Word button and I want all the words in the array to appear. How would I do this? Also could someone also explain why when nothing is entered into the input box "field is empty" does not appear?
function begin() {
var word = "List of words";
var i = returnword.length
if (userinput.length === 0) {
word = "Field is empty"
}
document.getElementById('message2').innerHTML = word
while (i--) {
document.getElementById('message').innerHTML = returnword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
var arrword = [];
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
Addword()
Your function contains an array arrword. If you keep it inside your function it will be reset every time you call the function. You need to keep your array of words outside the function
Empty input
The empty input message should be shown when you click on the Add word button. Check the input and display a message if needed
Display word
You can simply use join() to display you array
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');
function addWord() {
errorElement.innerHTML = "";
var word = inputElement.value;
if (word.trim() === "")
errorElement.innerHTML = "Empty input";
else
arrayOfWord.push(word);
inputElement.value = "";
}
function process(){
words.innerHTML = arrayOfWord.join(' - ');
}
#error {
color: tomato;
}
#words {
color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>
you can do something a bit clearer with jQuery! :)
if you handle the input with jquery you can write something like:
var arrWord = [] // your array
/* Attaching a click handler on your "Add Word" button that will
execute the function on user click */
$("#addWordButtonID").on("click", function () {
var wordTyped = $('#textInputID').val() // your var that collect userInput
if (wordTyped.length != 0) { // your if statement with length === 0 condition
arrWord.push(wordTyped) // adding word typed to the array
}
})
to add jquery to your html page, just add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in your html header
Hopefully you already have the right html. Then you can modify your script like below:
<script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
</script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">ProcessWords</button>
<input type="text" id="userinput" value=" " />
<div id="message2">
</div>
<div id="message">
</div>

javascript document.getElementById Loop

I am trying to make this print out the grades in the array that I created. I can get my for loop to cycle through all of the grades in the array but it only prints out the last grade. I have it set up to print the grade out each time the for loop completes one cycle, but as I said, it is only printing out the last grade. I also tried to use the .innerHTML but that did not work either as you will see in the code:
var arrayTest = [78, 65, 41, 99, 100, 81];
var arrayLength = arrayTest.length;
var midtermTest = 60;
var msg = "";
var grade;
arrayOfGrades();
addBonus();
function tellGrade() {
if (grade > 100) {
msg = "Grade is higher than 100!, " + grade;
}
else if (grade >= 90) {
msg = "You got an A " + grade + "!!, ";
}
else if (grade >= 80) {
msg = "You got a B " + grade + "!!, ";
}
else if (grade >= 70) {
msg = "You got a C " + grade + "!!, ";
}
else if (grade >= 60) {
msg = "You got a D " + grade + "!!, ";
}
else if (grade <= 59) {
msg = "You got a F " + grade + "!! :(, ";
}
else if (grade < 0) {
msg = "Grade is less than 0, " + grade;
}
}
function arrayOfGrades() {
for (var i = 0; i < arrayLength; i++) {
grade = arrayTest[i];
tellGrade(grade);
writeGrade();
}
}
function addBonus()
{
midtermTest = midtermTest + (midtermTest * .05);
grade = midtermTest;
tellGrade(grade);
writeMidtermGrade();
}
function writeGrade() {
//document.getElementById("test").innerHTML = "Test grade letter: " + msg.toString() + "<br />";
var el = document.getElementById('test');
el.textContent = "Test grade letter: " + msg.toString();
}
function writeMidtermGrade() {
var el = document.getElementById('midterm');
el.textContent = "Midterm test grade letter: " + msg.toString();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DecisionsAndLoopsAssignment1_Byrd</title>
<link href="css/default.css" rel="stylesheet" />
</head>
<body>
<div id="test">Missing grade!!</div>
<div id="midterm">Missing grade!!</div>
<script src="js/main.js"></script>
</body>
</html>
function writeGrade() overwrites whatever might already by in the elements it outputs to. So when called more than once only the last value is preserved. Using .innerHTML would do the same thing. Accumulating the content strings to a single var then making a single call to output them is one option to fix this.
I also note that you're passing temporary values around in global vars, which is generally considered poor form.
You are setting the ENTIRE content of the element not just adding on to it. This will constantly overwrite the work of the previous iteration of the loop, therefore you will only see the last result, cause computers are fast.
You have two options, read the textContent of the element, and continue adding to it. This concept is called self assignment.
var aMessage = "Hello, ";
aMessage += "World!";
console.log(aMessage") // => "Hello, World!"
Though general we would create a new element and append that element as a child
var msg = "A+"; // this should be a variable to our function vs a global va
function writeGrade() {
var el = document.getElementById('test');
var newEl = document.createElement("p");
newEl.textContent = "Test grade letter: " + msg.toString();
el.appendChild(newEl)
}
writeGrade()
<div id="test">
</div>

Javascript name generator

I'm trying to make JS output a full name based on input from both radio buttons and text. I'm having an issue as I want it to output the person's choice, yet whenever I click male or female, it's always displaying as Male (plus the text). The code I've got at the moment for the output is:
window.onload = initAll;
function initAll() {
document.getElementById("sillySubmit").onclick = function() {
document.getElementById("msgField").innerHTML = getSillyName();
return false;
}
}
function getSillyName() {
var x = $('input[id]').click(function() {
($('input[id]:checked').val());
});
var lastName1 = ["lots of names"];
var lastName2 = ["lots more names" ];
var lastNm = document.getElementById("lName").value.toUpperCase();
var validName = true;
if (lastNm == "") {
validName = false;
}
else {
var lastNum1 = lastNm.charCodeAt(0) - 65;
var lastNum2 = lastNm.charCodeAt((lastNm.length-1)) - 65;
if (lastNum1 < 0 || lastNum1 > 25 || lastNum2 < 0 || lastNum2 > 25) {
validName = false;
}
}
if (!validName) {
document.getElementById("lName").focus();
document.getElementById("lName").select();
return "I say. Something gone a bit squiffy here. Try again...";
}
return "Your name is " + x + ' ' + lastName1[lastNum1] + ' '
+ lastName2[lastNum2]; //add in comparisons later on
}
where 'x' is representing male and 'y' is female. What can I add/change so that it displays the correct preference?
I can't see your html, so I have to guess a lot. I assume you have a lot of input elements, all with an id-attribute, and your female/male buttons are two of them. Those buttons have a value being either 'on' or 'off', and in some browsers its always 'on'. So don't look for value. Further radio buttons have a property checked being either true or false.
You don't need to attach a click-handler to get the state.
So the first lines of your getSillyName() could look like:
function getSillyName() {
var x;
if (document.getElementById(/* female id here */).checked) {
x = 'Mrs.' // change string to whatever you want to see
} else if (document.getElementById(/* male id here */).checked) {
x = 'Mr.' // as above
} else x = 'cat'; // possibly both are unchecked
/* the very important next line in your code should be: */
console.log(x);
/* this important line move step by step further down your code */
console.log(/* and put in here what you want to check */);
/* rest of code here */
}
After that your element #msgField should show something.
What can I add/change so that it displays the correct preference?
If I understood correctly, the answer will be: parentheses.
The code will become:
"Your name is " + (x || y) + ' ' + lastName1[lastNum1] + ' ' + lastName2[lastNum2];
Try defining the first name before returning the value.
if(gender == 'male')
firstname = ...
else
firstName = ...
return 'Your name is ' + firstname + ' ' + lastName1[lastNum1] + ' ' + lastName2[lastNum2];
I hope that helps.

Making a quiz app, stuck on a function

I'm making a simple quiz app. But I'm stuck on ordering the functions.
Here is the code
// questions set
var qtnsSet = [
// format: [question, [comma, separated, options], index of correct ans. eg. 1]
["What is the full form of IP?", ["Internet Provider", "Internet Port", "Internet Protocol"], 2],
["Who is the founder of Microsoft?", ["Bill Gates", "Steve Jobs", "Steve Wozniak"], 0],
["Full name of IBM?", ["Internet Business Machine", "International Business Machine", "Indian Business Machine"], 1]
]
// init vars
var qtnNo = 0,
score = 0;
// define elements
var qtnContainer = $("qtn-container"),
optnsContainer = $("optns-container"),
submitBtn = $("submit-btn");
function $(id) { // Shortcut for document.getElementById
return document.getElementById(id);
}
function askQtn() { // ask question
var optns = qtnsSet[qtnNo][1], // options array
optnsHtml = "";
for (var optnNo = 0; optnNo < optns.length; optnNo++) {
optnsHtml += createOptnHtml(optnNo, optns[optnNo]);
}
qtnContainer.textContent = qtnsSet[qtnNo][0]; // question
optnsContainer.innerHTML = optnsHtml; // options
}
function createOptnHtml(optnNo, optn) { // create html elements for options
// eg. <li><input type='radio' name='optn' value='Option' id='optn-0'>
// <label for='optn-0'>Option</label></li>
return "<li><h3><input type='radio' name='optn' value='" + optn + "' id='optn-" + optnNo + "'>" +
" <label for='optn-" + optnNo + "'>" + optn + "</label></h3></li>";
}
function getGivenAns() { // get the answer given by user
var optns = document.getElementsByName("optn");
for (var optnNo = 0; optnNo < optns.length; optnNo++) {
if (optns[optnNo].checked) {
return optnNo; // index of the chosen answer
}
}
}
function checkAns() { // check if user's right or not
if (getGivenAns() == qtnsSet[qtnNo][2]) {
score += 6; // 6 points for right answer
}
}
function submitAns() {
if (qtnNo <= qtnsSet.length) {
if (getGivenAns()) {
checkAns();
qtnNo++;
askQtn();
} else {
alert("Please choose an answer.");
};
} else {
alert("Score: " + score);
};
}
window.addEventListener("load", askQtn, false);
submitBtn.addEventListener("click", submitAns, false);
I'm unable to configure the submitAns() function so that every thing works correctly.
How can I order the functions inside submitAns()?
getGivenAns()
Returns the index of the options, which can be 0 if the first option is selected which would evaluate to false here:
if (getGivenAns()) {
so just return true if an option is checked.
Also
if (qtnNo <= qtnsSet.length) {
Will be true after the last question it should just be
if (qtnNo < qtnsSet.length) {

Categories

Resources