Writing data into table with unknown number of rows - javascript

I am in a very basic "Intro to JS" course and my solving of this problem needs to equally basic and antiquated.
The exercise is supposed to display a table with a header with student names & scores of those scoring 90 or more. (Data is drawn from another js file.)
It then is supposed to display the total number of students and the total number of students scoring 90 or more. My math & if statement seem to be working, but the display is not...by a long shot. Any help would be greatly appreciated.
const ZERO = 0;
const NINETY_PERCENT = 90;
var studentName;
var studentScore;
var totalStudents;
var totalStudentsWithAs;
var studentRecords;
studentRecords = openStudentExamRecords();
function initializeExamRecords() {
totalStudents = ZERO;
totalStudentsWithAs = ZERO;
}
function startTable() {
document.write("<th>Student Name</th>");
document.write("<th>Exam Score</th>");
}
function printRecords() {
initializeExamRecords();
startTable();
while (studentRecords.readNextRecord()) {
studentName = studentRecords.getStudentName();
studentScore = studentRecords.getStudentScore();
totalStudents++;
if (studentScore >= NINETY_PERCENT) {
document.write("</td><td>");
document.write(studentName);
document.write("</td><td>");
document.write(studentScore);
totalStudentsWithAs++;
totalStudents = Number(totalStudents);
totalStudentsWithAs = Number(totalStudentsWithAs); alert("");
}
}
}
function endTable() {
document.write("</td></tr>");
}
function printTotals() {
printRecords();
document.write("</td><td>");
document.write("<tr><td colspan='5'> </td></tr>");
document.write("<tr><td colspan='5'>Total Students: <strong>" +
totalStudents + "</strong></td></tr>");
document.write("<tr><td colspan='5'>Total Sudents with A's: <strong>" +
totalStudentsWithAs + "</strong></td></tr>");
document.write("</td><tr>");
}
function endTable() {
document.write("</td></tr>");
}
printTotals();
endTable();

Related

adding event listeners in Javascript is doubling my (simple) maths

I will attempt to be as concise as possible, but am out of my depth (i should be in the baby pool :)
I'm trying to make a simple website for my son that presents a random sentence with a blank where an adverb should be. The user then has to guess which of the three randomised words presented below is an adverb. I have then tried to implement a scoring system which is where my problem lies.
I had it working OK, when the buttons were static, but since randomising and adding event listeners to the answer buttons it is adding two to the score instead of one. The problem code is towards the bottom (//add event listeners to buttons)
One further problem is that when someone answers the first question incorrectly my code says they have 'undefined correct answers'. I can't get that to say '0 correct answers'
<head>
<title>Adverb Kings</title>
</head>
<body>
<h1>Adverb Kings</h1>
<div id="sentence"></div>
<div>
<button type="button" onclick="right()"></button>
<button type="button" onclick="wrong()"></button>
<button type="button" onclick="wrong()"></button>
<div id="result"></div>
<div id="correct"></div>
<div id="attempted"></div>
</div>
<script>
//define right functions
function right() {
correctAlert();
correctAnswer();
answersAttempted();
}
//define wrong functions
function wrong() {
incorrectAlert();
answersAttempted();
}
//alert correct
function correctAlert() {
var element = document.getElementById("result");
element.classList.add("correct");
element.innerHTML = "Correct";
}
//alert incorrect
function incorrectAlert() {
var element = document.getElementById("result");
element.classList.add("incorrect");
element.innerHTML = "Incorrect, try again.";
}
//tracking correct answers
function correctAnswer() {
if (sessionStorage.correct) {sessionStorage.correct = Number(sessionStorage.correct)+1;
} else {
sessionStorage.correct = 1;
}
}
//tracking attempted questions count
function answersAttempted() {
if (typeof(Storage) !== "undefined") {
if (sessionStorage.attempts) {
sessionStorage.attempts = Number(sessionStorage.attempts)+1;
} else {
sessionStorage.attempts = 1;
}
document.getElementById("attempted").innerHTML = "You have attempted " + sessionStorage.attempts + " question(s) in this session and got " + sessionStorage.correct + " correct" ;
} else {
document.getElementById("attempted").innerHTML = "Sorry, your browser does not support web storage...";
}
}
//create sentence array
var sentence;
sentence = ['The people _______ went crazy about the new game options', 'The man _______ slipped his hands around his desk handle', 'He _______ typed a new password for his school account'];
//randomise sentence array
var el = document.getElementById('sentence');
el.textContent = sentence[Math.floor(Math.random() * sentence.length)];
//set order of words in order to randomise
var orders = [0, 1, 2];
shuffle(orders);
//add event listeners to buttons
var buttons = document.getElementsByTagName("button");
buttons[orders[0]].addEventListener('click', right);
buttons[orders[1]].addEventListener('click', wrong);
buttons[orders[2]].addEventListener('click', wrong);
//create and randomise adverb array
var adverbs = ['slowly', 'quickly', 'insanely'];
buttons[orders[0]].textContent = adverbs[Math.floor(Math.random() * adverbs.length)];
//create and randomise other words
var other1 = ['burger', 'insane', 'ugly'];
buttons[orders[1]].textContent = other1[Math.floor(Math.random() * other1.length)];
var other2 = ['sausage', 'fist', 'gun'];
buttons[orders[2]].textContent = other2[Math.floor(Math.random() * other2.length)];
//shuffle position of adverb
function shuffle(array) {
array.sort(() => Math.random() - 0.5);
}
</script>
</body>
</html>```
You are adding the event listeners both in the HTML and JS.
Remove the onclick="..." part of the buttons in the HTML and all should be good.
To stop the number being undefined, set sessionStorage.correct to 0 before you call any functions:
<script>
sessionStorage.correct = 0;
...
You have added event listener twice on in HTML and one in js code due to which it is hitting twice.
regarding the undefined value, when hitting incorrect first-time session storage is not initialized due to which it is showing undefined. please check below js code where I have commented the js event listener and initialize the sessionstorage.correct and now it is working fine.
code
//define right functions
function right() {
correctAlert();
correctAnswer();
answersAttempted();
}
//define wrong functions
function wrong() {
incorrectAlert();
answersAttempted();
}
//alert correct
function correctAlert() {
var element = document.getElementById("result");
element.classList.add("correct");
element.innerHTML = "Correct";
}
//alert incorrect
function incorrectAlert() {
var element = document.getElementById("result");
element.classList.add("incorrect");
element.innerHTML = "Incorrect, try again.";
}
//tracking correct answers
function correctAnswer() {
if (sessionStorage.correct) {sessionStorage.correct = Number(sessionStorage.correct)+1;
} else {
sessionStorage.correct = 1;
}
}
//tracking attempted questions count
function answersAttempted() {
if (typeof(Storage) !== "undefined") {
if (sessionStorage.attempts) {
sessionStorage.attempts = Number(sessionStorage.attempts)+1;
} else {
sessionStorage.attempts = 1;
}
// initializing sessionStorage.correct
if(!sessionStorage.correct) {
sessionStorage.correct=0;
}
document.getElementById("attempted").innerHTML = "You have attempted " + sessionStorage.attempts + " question(s) in this session and got " + sessionStorage.correct + " correct" ;
} else {
document.getElementById("attempted").innerHTML = "Sorry, your browser does not support web storage...";
}
}
//create sentence array
var sentence;
sentence = ['The people _______ went crazy about the new game options', 'The man _______ slipped his hands around his desk handle', 'He _______ typed a new password for his school account'];
//randomise sentence array
var el = document.getElementById('sentence');
el.textContent = sentence[Math.floor(Math.random() * sentence.length)];
//set order of words in order to randomise
var orders = [0, 1, 2];
shuffle(orders);
//add event listeners to buttons
var buttons = document.getElementsByTagName("button");
// buttons[orders[0]].addEventListener('click', right);
// buttons[orders[1]].addEventListener('click', wrong);
// buttons[orders[2]].addEventListener('click', wrong);
//create and randomise adverb array
var adverbs = ['slowly', 'quickly', 'insanely'];
buttons[orders[0]].textContent = adverbs[Math.floor(Math.random() * adverbs.length)];
//create and randomise other words
var other1 = ['burger', 'insane', 'ugly'];
buttons[orders[1]].textContent = other1[Math.floor(Math.random() * other1.length)];
var other2 = ['sausage', 'fist', 'gun'];
buttons[orders[2]].textContent = other2[Math.floor(Math.random() * other2.length)];
//shuffle position of adverb
function shuffle(array) {
array.sort(() => Math.random() - 0.5);
}

How to compare numerical values of two innerHTML elements? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to compare the numerical values of elements in Javascript (Still learning, so I am grateful for any help).
Currently I have the code:
if (parseInt(document.getElementById("player1").innerHTML) > parseInt(document.getElementById("player2").innerHTML)) {
document.getElementById("gametitle").innerHTML = "Player 1 wins!"
} else if (parseInt(document.getElementById("player2").innerHTML) > parseInt(document.getElementById("player1").innerHTML)) {
document.getElementById("gametitle").innerHTML = "Player 2 wins!"
} else if (parseInt(document.getElementById("player1").innerHTML) > parseInt(document.getElementById("computer1").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You win!"
} else if (parseInt(document.getElementById("player1").innerHTML) > parseInt(document.getElementById("computer2").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You win!"
} else if (parseInt(document.getElementById("player1").innerHTML) > parseInt(document.getElementById("computer3").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You win!"
} else if (parseInt(document.getElementById("computer1").innerHTML) > parseInt(document.getElementById("player1").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You lose!"
} else if (parseInt(document.getElementById("computer2").innerHTML) > parseInt(document.getElementById("player1").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You lose!"
} else if (parseInt(document.getElementById("computer3").innerHTML) > parseInt(document.getElementById("player1").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You lose!"
} else {
document.getElementById("gametitle").innerHTML = "There's an error!"
}
Any help would be greatly appreciated.
The issue here is that you are using the innerHTML when you should be using innerText. See Difference between innerText and innerHTML in javascript
Also, since you mentioned you are new to programming, here are some best practices for you.
If you are going to be comparing the values multiple times you should save the value in a variable instead of constantly using the resources to retrieve the same value.
var player1 = parseInt(document.getElementById("player1").innerText)
var player2 = parseInt(document.getElementById("player2").innerText)
var player3 = parseInt(document.getElementById("player3").innerText)
var computer1 = parseInt(document.getElementById("computer1").innerText)
var computer2 = parseInt(document.getElementById("computer2").innerText)
var computer3 = parseInt(document.getElementById("computer3").innerText)
You are also comparing multiple scores using the same logic so instead of repeating this code you should write a function. A function is a block of code that you can name and call later, see here for more information: http://www.w3schools.com/js/js_functions.asp
function compareScores(playerScore,computerScore){
if (playerScore > computerScore){
document.getElementById("gametitle").innerText = "You win!"
} else if (computerScore > playerScore){
document.getElementById("gametitle").innerText = "You lose!"
} else {
document.getElementById("gametitle").innerText = "You Tied!"
}
}
Now you just need to call this function with the values for each set.
compareScores(player1,computer1)
compareScores(player2,computer2)
compareScores(player3,computer3)
Don't use innerHTLM, as it returns... HTML. parseInt won't work on that. Use innerText instead:
if (parseInt(document.getElementById("computer3").innerText) > parseInt(document.getElementById("player1").innerText)) {
// Do something
}
Also, it will help you a lot if you first extract the values, then compare them:
var computer3Score = parseInt(document.getElementById("computer3").innerText);
var player1Score = parseInt(document.getElementById("player1").innerText);
if (computer3Score > player1Score) {
// do something
}
Relying on the DOM to store the data is a bad practice. What if you want to use the same logic and data with a different view ? You would have to refactor the entire code. Rather do the opposite, generate the DOM based on a data structure that is the unique source of data for all your application. Thus, you don't need the DOM to manage the data anymore.
In the example below, the data source is an array called "players". Try to add a new player to the array and see how easier it is to manage. Moreover, if you want to change the HTML of the score board, you just have to edit the template once for all players. This template is located in the function called "dataToHtml".
var players, tbody, button, indexOf;
players = [
{ name: "John", score: 2 },
{ name: "Mary", score: 1 },
{ name: "Bot 1", score: 4 },
{ name: "Bot 2", score: 3 }
];
indexOf = Array.prototype.indexOf;
button = document.getElementsByTagName("button")[0];
tbody = document.getElementsByTagName("tbody")[0];
tbody.innerHTML = dataToHtml();
button.onclick = function () {
var i, best, trs;
best = bestScore();
trs = tbody.childNodes;
for (i = 0; i < trs.length; i++) {
trs[i].style.backgroundColor = (
players[i].score == best ? "yellow" : "white"
);
}
};
tbody.onclick = function (ev) {
var i, tr, score, name;
tr = ev.target.parentNode;
i = indexOf.call(this.childNodes, tr);
name = players[i].name;
score = prompt("New score for " + name + " :");
if (!isNaN(score = parseInt(score, 10))) {
tr.childNodes[1].textContent = score;
players[i].score = score;
}
};
function bestScore () {
var i, best;
for (i = 0; i < players.length; i++) {
if (i == 0 || players[i].score > best) {
best = players[i].score;
}
}
return best;
}
function dataToHtml () {
var i, html = "";
for (i = 0; i < players.length; i++) {
html += ""
+ "<tr>"
+ "<td>" + players[i].name + "</td>"
+ "<td class=\"score\">" + players[i].score + "</td>"
+ "</tr>";
}
return html;
}
body, button {
font: normal 12px Arial;
}
div {
display: inline-block;
vertical-align: middle;
text-align: center;
}
table {
margin-right: 1em;
}
table, th, td {
border-collapse: collapse;
border: 1px solid #999;
padding: .25em;
}
td.score {
text-align: right;
}
<div>
<table>
<thead>
<tr>
<th>player</th>
<th>score</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div><div>
<p><button type="button">Who wins ?</button></p>
<p>click a row<br />to change<br />the score</p>
</div>

My generated french word duplicates? When it shouldn't be

I've sorted this but now it's came back on... I've tried changing the for loops but it still seems to generate duplicate French words. It's suppose to not show the french word twice in the application run.
My jsFiddle is an exact replica:
http://jsfiddle.net/jamesw1/w8p7b6p3/17/
Javascript:
//James Wainwright's Mobile Apps Assignment
//Arrays of french and english words.
var
RanNumbers = new Array(6),
foreignWords = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf', 'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois', 'vingt-quatre', 'vingt-cinq', 'vingt-six', 'vingt-sept', 'vingt-huit', 'vingt-neuf', 'trente'],
translate = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-three', 'twenty-four', 'twenty-five', 'twenty-six', 'twenty-seven', 'twenty-eight', 'twenty-nine', 'thirty'],
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
//Generate random numbers and make sure they aren't the same as each other.
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
while(temp==correctAns){
temp = Math.floor(Math.random() * 30);
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu using for loop. This loop runs once (on document load)
document.getElementById('generatedWord').textContent = foreignWords[number];
var correctAnswerIndex = Math.floor(Math.random() * 6);
//If it's 0...Change it.
if(correctAnswerIndex == 0)
{
correctAnswerIndex++;
}
//Create a select menu of the options...Add the correct answer randomly into the menu.
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i < RanNumbers.length; i++) {
//This randomizes where the correct answer will be.
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += "</select>";
//Output the previous.
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Declare variables 'outside' the onclick function so it ensures they work correctly.
var numGames = 5;
var numGuesses = 1;
var correct = 0;
var wrong = 0;
var prevNumber;
var counter = 0;
var outputted = '';
//Create arrays that will hold the options they chose, the correct answer for that particular question, and ofcourse the generated word.
var guessedList = new Array(6);
var correctList = new Array(6);
var wordGenerated = new Array(6);
//On click, Get new word, Calculate how many they got right/wrong, Show the user what they entered, show them the correct values they should've guessed and more...
document.getElementById('submitAns').onclick = function () {
//Declare variables for function.
prevNumber = number;
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
document.getElementById('numGuess').innerHTML = "Question #" + numGuesses;
//Check if guess is right or wrong, if right add 1 to correct pile..Visa versa.
var
genWord = document.getElementById('generatedWord').textContent,
select = document.getElementById('guesses'),
selectedText = select.options[select.selectedIndex].text;
prevNumber === arrayValueIndex(translate, selectedText) ? correct++ : wrong++;
function wordGen() {
for (var j = 0; j < RanNumbers.length; j++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
while(temp==correctAns){
temp = Math.floor(Math.random() * 30);
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[j] = temp;
}
}
//Generate a word here. ( call wordGen() )
wordGen();
//Create dynamic select menu for options they have to choose from.
document.getElementById('generatedWord').textContent = foreignWords[number];
//Generate a random number, so that the 'Correct' answer can be randomly put in a position in the select menu. (It won't always be in the same position...It changes depending on the random number
var correctAnswerIndex = Math.floor(Math.random() * 6);
//If it's 0...Change it.
if(correctAnswerIndex == 0)
{
correctAnswerIndex++;
}
//Create a select menu of the options...Add the correct answer randomly into the menu.
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i < RanNumbers.length; i++) {
//This randomizes where the correct answer will be.
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += "</select>";
//Outputting to the html page.
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Checking of the answers below, Accumilating correct and wrong answer.
//Count number of guesses
numGuesses++;
//Counter for placing guessed, correct and foreign word into there arrays.
counter++;
wordGenerated[counter] = foreignWords[number];
guessedList[counter] = document.getElementById('guesses').options[select.selectedIndex].text;
correctList[counter] = translate[number];
//Once the application has finished...It will produce the following output.
if (numGuesses == 6) {
document.getElementById('generatedWord').innerHTML = "<span style='font-size:12px;color:red';>Please click for a new game when ready!</span><br /><p>You got " + wrong + " questions wrong " + "<br />You got " + correct + " questions correct";
$('#submitAns').hide();
outputted = "<table>";
for(var d=1;d<wordGenerated.length;d++){
outputted += "<tr><td><span id='guessedWord'>Question " + d + ":</td> <td>Generated word: " + wordGenerated[d] + "</td> <td>Guessed Word: " + guessedList[d] + "</td> <td><span id='correctWord'>Correct Word: " + correctList[d] + "</span></td></td>";
}
outputted += "</table>";
outputted += "<style type='text/css'>#hint{ display:none; }</style>";
//Output it to the html page.
document.getElementById('details').innerHTML = outputted;
}
};
document.getElementById('hint').onclick = function () {
alert(correctAns.charAt(0));
};
Html:
<div data-role="page" id="page1" data-add-back-btn="true">
<div data-role="header">
<h1>James' Translation Guessing Game</h1>
</div>
<div data-role="content" class="main">
<h2 id="display" style="color:rgba(204,51,204,1);">Guess what the generated french word translates to in English!</h2><br />
<!-- What question we're upto -->
<h2 id="numGuess">Question #</h2 >
<!-- The generated French Word Aswell as end of app details-->
<div align="center" class="frenchWord" style="position:">
<!--Generated french word details-->
<div style="background-color:rgba(51,51,51,0.5);border-radius:4px 10px 2px;"align="center" id="generatedWord"></div>
<br />
<br />
<!-- Show the user there guessed answers, correct and foreign word -->
<div id="details"></div>
</div>
<!-- Select menu output -->
<div align="center" id="output"></div>
<img id="hintImg" style="" src="images/hint.png" alt="Hint" />
<!-- Buttons, Call Functions -->
<button type="button" style='opacity:0.5' id="submitAns" onClick="translate();">Check</button>
<input type="button" value="New Game" onClick="document.location.reload(true)">
<script>
//Simple animation
$(document).ready(function(){
$("#generatedWord").animate({
opacity: 0.8,
margin: "40px 0px 100px 0px",
width: "20%",
padding: "30px",
}, 1500 );
});
</script>
</div>
<div data-role="footer">
<h4>James Wainwright</h4>
</div>
</div>
This might do it. Before assigning a number to the RanNumbers array I delete it from the original RanNumbers array to prevent duplication. It might make more sense to just maintain a separate array of numbers to be used in the questions but I tried to change as little as possible.
Updated Fiddle
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * RanNumbers.length);
while(temp==correctAns){
temp = Math.floor(Math.random() * RanNumbers.length);
delete(RanNumbers.indexOf(temp)); // delete it so we can add it down below
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}

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) {

Create form for function Html

This is my problem, hope get some support for this.
This is my function.
function show(n,q)
{
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){document.write(t+ " ");}
else{document.write("");}
}
}
show(1000,3);
With two inputs: number n and the exponent q it will solve all the numbers smaller than n which the sum of all the q-exponented of its digits is equal to itself.
For example: q=3, n=200, we have the number 153 because: 1^3 + 5^3 + 3^3 = 153
This function is OK, but due to my bad javascript skill, I dont know how to create a form alowing to enter n and q into 2 boxes, then click button "Show" we have results in the third box.
I have tried this below code, but it does not work :(
<input id='number' type='text' />
<input id='exp' type='text' />
<button onclick='javascript:show()'>Show</button>
<div id='res' style='width:100%;height:200px'></div>
<script>
function show() {
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){
out.innerHTML+=t+ " ";
}
else{
out.innerHTML+="";
}
}
}
</script>
In additon, I want to do it myself, could you guys tell me where i can find guide for this problem.
Thanks.
Your code has some punctuation issues.
Try to replace:
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
by
var n=document.getElementById('number').value,
q=document.getElementById('exp').value,
out=document.getElementById('res');
out.innerHTML="";
The code looks fine and will do what you are trying to do. Just there are some , (Comma) instead of ; (Semi-colon) in your code. Change them and then try.
Check the solution here.
http://jsfiddle.net/JszG2/
var n=document.getElementById('number').value;
var q=document.getElementById('exp').value;
out=document.getElementById('res');
Below is solution using JQuery....
<script>
function show() {
var num = parseInt($('#number').val());
var exp = parseInt($('#exp').val());
out = $('#res');
var num = document.getElementById('number').value;
var exp = document.getElementById('exp').value;
out = document.getElementById('res');
out.innerHTML = "";
for (p = 1; p <= num; p++) {
q = p.toString().length;
v = 0;
for (i = q - 1; i >= 0; i--) {
v = v+ Math.pow((Math.floor(p / Math.pow(10, i)) % 10), exp);
}
if (v == p) {
out.innerHTML += v + " ";
}
else {
out.innerHTML += "";
}
}
}
</script>

Categories

Resources