Javascript produced tables sometimes fail - javascript

The last table and sometimes the table before as well will not load correctly sometimes which breaks the loop I have.
This error in my code started happening since I added the table creation part of my javascript.
My question is why because the way i have it works majority of the time but in these instances it does not. I am running it on jsfiddle.
Any help is appreciated.
Lastly I want to add in a picture of a star where the "new content" phrases are if you could help with that as well you would be of much help.
<html>
<head>
</head>
<body>
<input type="button" value="Delete" onclick="deleteRow()">
<table id="myTable1" border="1"></table>
<br>
<table id="myTable2" border="1"></table>
<br>
<table id="myTable3" border="1"></table>
<br>
<h1 class="box">
<table style="width:100%" id = "table1">
</table>
<br>
<p id="time"></p>
<span id="num1"></span>
+ <span id="num2"></span> =
<input id="answer" type="text" size="3"/>
<button onclick = "math1()">Check</button>
</h1>
</body>
</html>
That is the HTML the Javascript will follow this.
window.onload = function uphigh() {
document.getElementById("num1").innerHTML = parseInt(Math.floor((Math.random() * 10) + 1));
var num1 = document.getElementById("num1").innerHTML;
document.getElementById("num2").innerHTML = parseInt(Math.floor((Math.random() * 10) + 1));
var num2 = document.getElementById("num2").innerHTML;
num1 = parseInt(num1);
num2 = parseInt(num2);
var num3 = num1 + num2;
insRow(2, 5, 'myTable1', num1);
insRow(2, 5, 'myTable2', num2);
insRow(4, 5, 'myTable3', num3);
};
function uphigh() {
document.getElementById("num1").innerHTML = parseInt(Math.floor((Math.random() * 10) + 1));
var num1 = document.getElementById("num1").innerHTML;
document.getElementById("num2").innerHTML = parseInt(Math.floor((Math.random() * 10) + 1));
var num2 = document.getElementById("num2").innerHTML;
num1 = parseInt(num1);
num2 = parseInt(num2);
var num3 = num1 + num2;
insRow(2, 5, 'myTable1', num1);
insRow(2, 5, 'myTable2', num2);
insRow(4, 5, 'myTable3', num3);
}
function math1() {
var num1 = document.getElementById("num1").innerHTML;
var num2 = document.getElementById("num2").innerHTML;
num1 = parseInt(num1);
num2 = parseInt(num2);
var num0 = num1 + num2;
var answer = document.getElementById("answer").value;
answer = parseInt(answer);
if (num0 == answer) {
var things = ['Way to Go!!!', 'Congratulations!!!', 'Correct!!!', 'Your Doing Great!!!'];
var thing = things[Math.floor(Math.random() * 4)];
alert(thing);
deleteRow();
uphigh();
document.getElementById("answer").value = "";
} else {
alert("Incorrect answer!! \nPlease Try Again");
document.getElementById("answer").value = "";
}
}
function insRow(rows, col, tableId, num) {
for (var j = 0; j < rows; j++) {
var x = document.getElementById(tableId).insertRow();
for (var i = 0; i < col; i++)
var y = x.insertCell(0);
}
var row = parseInt(num / 5);
var cols = num % 5;
var x = document.getElementById(tableId).rows;
if (row != 0) {
for (var j = 0; j < row; j++) {
x = document.getElementById(tableId).rows;
var y = x[j].cells;
for (var i = 0; i < 5; i++) {
y[i].innerHTML = "NEW CONTENT";
}
}
}
var y = x[row].cells;
for (var i = 0; i < cols; i++) {
y[i].innerHTML = "NEW CONTENT";
}
}
function deleteRow() {
for (var j = 0; j < 2; j++)
document.getElementById('myTable1').deleteRow();
for (var j = 0; j < 2; j++)
document.getElementById('myTable2').deleteRow();
for (var j = 0; j < 4; j++)
document.getElementById('myTable3').deleteRow();
}
Building this website for helping children learn basic math.
Do not know how to add a link to fiddle.

Related

Multiplication Table in javascript and how about to align the row

I tried to a do Multiplication Table in JS and I want to print in <p> element out (Use DOM and not use document.write method).
I tried to use " " or "\t" to align column , but when number is double digit (from x3 column) , it got typographic issue.
Does it any ways could solve this problem?
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
for (var j = 1; j <= 9; j++) {
s = s + j + "*" + i + " = " + (i * j) + " ";
}
s = s + "<br>";
}
p1.innerHTML = s;
<pre id="printout"></pre>
Instead of printing table column wise, print row wise.
And wrap your each table in a div, so that aligning them becomes easy.
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
s = s + "<div>";
for (var j = 1; j <= 9; j++) {
s = s + i + "*" + j + " = " + (i*j) + "<Br/>" ;
}
s = s + "</div>";
}
p1.innerHTML = s;
Little bit CSS
#printout {
display:flex;
flex-wrap:wrap;
}
#printout div {
padding:10px;
min-width:100px
}
https://jsfiddle.net/wkg92rud/
Inspiring from #Andreas suggestion, Using <table>
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
let row = document.createElement("tr");
for (var j = 1; j <= 9; j++) {
let col = document.createElement("td");
col.innerText = j + "*" + i + " = " + (i * j);
row.append(col);
}
p1.append(row);
}
td {
padding: 2px 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<table id="printout"></table>
</body>
</html>
#Dalvik method is the correct way, styling and alignment should be done through CSS.
However, in other environments like command line, or if you are doing this as an exercise to learn JS you can use string padding, here is an example:
const p1 = document.getElementById("printout");
const LONGEST_ENTRY = 9; // Longest string you will have is 9 characters long
const entries = []
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
const entry = `${j}*${i} = ${(i*j)}`.padEnd(LONGEST_ENTRY, " ") ; // use string interpolation, then pad the string with spaces until the length of LONGEST_ENTRY is reached
entries.push(entry); // store all the entries in an array
}
entries.push("<br/>"); // add a line break at the end of each row
}
p1.innerHTML = entries.join(''); // join all the elements
Here is a jsfiddle as an example

How to sum the products of two different functions into a new function?

Right now I have two different functions that calculate the total costs of two different sections on the menu, the Appetizers & Main Dishes. Now what I am trying to do is create a third function that will give me a grand total of both the Appetizers & Main Dishes costs.
Here are my two functions:
function AppSubTotal() {
var guestsQTY = +document.getElementById('guests').value || 0,
input = document.getElementsByName("app"),
appItemTotal = 0;
var appsubtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) appItemTotal += +input[i].value;
}
document.getElementById("appsubtotal").value = "$" + (appItemTotal * guestsQTY * percentage).toFixed(2);
appsubtotal.innerText = appsubtotal;
}
function MainDishSubTotal() {
var guestsQTY = +document.getElementById('guests').value || 0,
input = document.getElementsByName("maindish"),
maindishItemTotal = 0;
var maindishtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) maindishItemTotal += +input[i].value;
}
document.getElementById("maindishtotal").value = "$" + (maindishItemTotal * guestsQTY * percentage).toFixed(2);
maindishtotal.innerText = maindishtotal;
}
This is how I have the Appetizers Total & Main Dishes Total displayed in HTML
<label>
<h1>
Total Appetizers Costs:
<input value="$0.00" readonly="readonly" type="text" id="appsubtotal"/>
</h1>
</label>
<label>
<h1>
Total Main Dish Costs:
<input value="$0.00" readonly="readonly" type="text" id="maindishtotal"/>
</h1>
</label>
I started a new function that will hold the grand total. I tried following another tutorial on how this can be done but it doesn't seem to be working for me but this is what I have so far.
function GrandTotal() {
var totalApp = appsubtotal.innerText || 0;
var totalMain = maindishtotal.innerText || 0;
document.getElementById('grandtotal').innerText = Number(totalApp) + Number(totalMain);
}
document.addEventListener('keyup', function() {
AppSubTotal();
MainDishSubTotal();
});
And then I want the grand total to be updated automatically as the user is selecting different items of the menu in HTML like this:
<label>
<h1>
Your Grand Total is:
<input value="$0.00" readonly="readonly" type="text" id="grandtotal"/>
</h1>
</label>
You need to call GrandTotal() at the end of each of other 2 functions:
function AppSubTotal() {
var guestsQTY = +document.getElementById('guests').value || 0,
input = document.getElementsByName("app"),
appItemTotal = 0;
var appsubtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) appItemTotal += +input[i].value;
}
document.getElementById("appsubtotal").value = "$" + (appItemTotal * guestsQTY * percentage).toFixed(2);
appsubtotal.innerText = appsubtotal; //here sub total updated
GrandTotal();
}
function MainDishSubTotal() {
var guestsQTY = +document.getElementById('guests').value || 0,
input = document.getElementsByName("maindish"),
maindishItemTotal = 0;
var maindishtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) maindishItemTotal += +input[i].value;
}
document.getElementById("maindishtotal").value = "$" + (maindishItemTotal * guestsQTY * percentage).toFixed(2);
maindishtotal.innerText = maindishtotal; //here main dish updated
GrandTotal();
}
function AppSubTotal() {
...
return appsubtotal; // assuming this is a number
}
function MainDishSubTotal() {
...
return maindishtotal; // assuming this is a number
}
... // in some other function
const checkTotal = MainDishSubtotal() + AppSubTotal();
// do whatever you want with this value now, including putting it as the text value somewhere
I don't know the full context of your code, but a little refactoring can help you out:
// it is better to keep compoments references if you are going to use them
// more tha once
var appSubtotalField = document.getElementById("appsubtotal");
function setAppSubTotal() {
appSubtotalField.value = "$" + calculateAppSubTotal().toFixed(2);
appsubtotal.innerText = appsubtotal;
}
function calculateAppSubTotal() {
var guestsQTY = document.getElementById('guests').value || 0,
input = document.getElementsByName("app"),
appItemTotal = 0;
var appsubtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) appItemTotal += input[i].value;
}
return appItemTotal * guestsQTY * percentage;
}
var mainDishTotalField = document.getElementById("maindishtotal");
function setMainDishSubTotal() {
mainDishTotalField.value = "$" + calculateMainDishTotal().toFixed(2);
maindishtotal.innerText = maindishtotal;
}
function calculateMainDishTotal() {
var guestsQTY = document.getElementById('guests').value || 0,
input = document.getElementsByName("maindish"),
maindishItemTotal = 0;
var maindishtotal = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) maindishItemTotal += input[i].value;
}
return maindishItemTotal * guestsQTY * percentage;
}
function setGrandTotal() {
document.getElementById('grandtotal').innerText =
calculateAppSubTotal() + calculateMainDishTotal();
}
Then you can complete your initialization
This currently listens to every keyup event. You may want to add a button or other mechanism to trigger this calculation.
document.addEventListener('keyup', function() {
setAppSubTotal();
setMainDishSubTotal();
});

Start new game function not working

Can someone please help me. I don't know where I have gone wrong. The main thing not working is my start new game function but I don't know where I have gone wrong. Thanks in advance.
This is my fiddle
http://jsfiddle.net/Matt1990/jL7f3p39/25/
This is my javascript
enter code here
var Array = ["monitor", "program", "keyboard", "gaming", "harddisk", "software", "printer", "scanner", "firewall", "desktop", "system", "malware", "windows"];
var word;
var guessCount = 0;
var guess;
var input;
var wordLength;
var wordSubstring;
var currentWord;
function startGame() {
guess = "";
guessCount = 10;
word = Array[Math.floor(Math.random() * Array.length)];
currentWord = 0;
wordLength = word.length;
wordSubstring = currentWord.substring;
console.log(word);
var myElement = document.getElementById("button").innerHTML = "Click to guess";
var myPicElement = document.getElementById("hangimage").src = "http://fetlar.kingston.ac.uk/pp/hangman10.jpg";
for (var count = 0; count < word.length; count++) {
guess = guess + "-";
}
document.getElementById("guess").innerHTML = guess;
}
function guessLetter() {
var correct = 0;
var inputBox = document.getElementById("guessinput");
input = inputBox.value;
for (var count = 0; count < wordLength; count++) {
if (input == word.substring(count, count + 1)) {
correct++;
guess = guess.substring(0, count) + input + guess.substring(count + 1, guess.length + 1);
document.getElementById("guess").innerHTML = guess;
}
}
if (correct == 0) {
guessCount--;
}
var url = document.getElementById("hangimage").src = "http://fetlar.kingston.ac.uk/pp/hangman" + guessCount + ".jpg";
if (guess == word) {
document.getElementById("hangimage").src = "http://fetlar.kingston.ac.uk/pp/hangman_win.jpg";
alert("You guessed the word correctly. You win!");
}
if (guess == 0 + word) {
document.getElementById("hangimage").src = "http://fetlar.kingston.ac.uk/pp/hangman0.jpg";
}
}
startGame();
document.getElementById("button").onclick = guessLetter;
function startNewGame(showMessage) {
guess = "";
guessCount = 10;
word = Array[Math.floor(Math.random() * Array.length)];
currentWord = 0;
wordLength = word.length;
wordSubstring = currentWord.substring;
console.log(word);
var myElement = document.getElementById("button").innerHTML = "Start New Game";
for (var count = 0; count < word.length; count++) {
guess = guess + "-";
document.getElementById("guess").innerHTML = guess;
}
}
and this is my HTML
<fieldset>
<div style="text-align: center;">
<h1>Hangman</h1>
<h2> Can you save the stick man? <h2>
<img id="hangimage" src="http://fetlar.kingston.ac.uk/pp/hangman9.jpg" />
<div id="guess" style="font-size: 2.5em; font-family: arial; color: red;">- - - - - - - </div>
<input id="guessinput" type="text" size="2" />
<button id="button">Click to guess</button>
<br/>
<div>Hint:The word is a computer-related term</div>
<button id="button">Start New Game</button>
</fieldset>
As i can see
HTML
<button id="button2">Start New Game</button>
JAVASCRIP
document.getElementById("button").onclick = guessLetter;
// add this
document.getElementById("button2").onclick = startNewGame;
http://jsfiddle.net/rnrlabs/jL7f3p39/30/

no output is displaying

The below code is my html code
Star.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="CssText.css">
</head>
<body>
<form>
Enter number of rows: <input type="text" name="t1" /> <input
type="button" value="Display Diomond"
onclick="return myFunction(this.form)" />
</form>
<p id="p"></p>
<script src="StarPrint.js"></script>
</body>
</html>
The below code is my javascript code
StarPrint.js
function myFunction(form) {
var no;
no = form.t1.value;
no = no / 2;
var no2 = no;
var no3 = no;
var no4 = no;
var no5 = no;
var no6 = no;
for ( var i = 0; i < no; i++) {
for ( var index = 0; index < no2; index++) {
document.getElementById("p").innerHTML ="&nbsp&nbsp";
}
no2 = no2 - 1;
for ( var index2 = 0; index2 < (i * 2) + 1; index2++) {
document.getElementById("p").innerHTML = "*";
}
document.getElementById("p").innerHTML="</br>";
}
document.getElementById("p").innerHTML="&nbsp&nbsp";
for ( var i = 0; i < no3 + 1; i++) {
for ( var index = 0; index <= i; index++) {
document.getElementById("p").innerHTML = "&nbsp&nbsp";
}
for ( var index2 = 0; index2 < (no4 * 2) - 3; index2++) {
document.getElementById("p").innerHTML = "*";
}
no4 = no4 - 1;
document.getElementById("p").innerHTML = "</br>&nbsp";
}
}
I want to print pattern of diamond structure.The above program was working when I used document.write instead of document.getElementById("p").innerHTML with some modification.Where is that error I am not getting it.
You are replacing the content of p every time you call document.getElementById("p").innerHTML =.
Instead, save the text into a variable and only assign it to p at the end:
function myFunction(form) {
var no;
no = form.t1.value;
no = no / 2;
var no2 = no;
var no3 = no;
var no4 = no;
var no5 = no;
var no6 = no;
var diamond = "";
for ( var i = 0; i < no; i++) {
for ( var index = 0; index < no2; index++) {
diamond +="&nbsp&nbsp";
}
no2 = no2 - 1;
for ( var index2 = 0; index2 < (i * 2) + 1; index2++) {
diamond += "*";
}
diamond+="</br>";
}
diamond+="&nbsp&nbsp";
for ( var i = 0; i < no3 + 1; i++) {
for ( var index = 0; index <= i; index++) {
diamond += "&nbsp&nbsp";
}
for ( var index2 = 0; index2 < (no4 * 2) - 3; index2++) {
diamond += "*";
}
no4 = no4 - 1;
diamond += "</br>&nbsp";
}
document.getElementById("p").innerHTML = diamond;
}
Working Example - http://jsfiddle.net/fdadE/
You are not appending the stuff you want, but just assigning. Replace all = with += like below:
document.getElementById("p").innerHTML = "&nbsp&nbsp";
to
document.getElementById("p").innerHTML += "&nbsp&nbsp";

Evaluating specific array value using jQuery or JavaScript

I have 160 inputs in my page. I want to add every 8 inputs and output it elsewhere. Instead of manually using
var total1 = inputVals[0] + inputVals[1] + inputVals[2] + inputVals[3] + inputVals[4] + inputVals[5] + inputVals[6] + inputVals[7] + inputVals[8];
I want a function with which you can just specify the starting and ending index like addarray(9, 17) and it will add all the values between and will return it. I prefer the function to be in javascript but jquery is OK.
Suppose you have <input> elements defined as:
<input type="text" class="myInput" />
<input type="text" class="myInput" />
<input type="text" class="myInput" />
...
You can create a method that does the job with the help of jQuery:
function add(start, end) {
var total = 0;
$(".myInput").slice(start, end).each(function() {
total += +this.value;
});
return total;
}
The same method in pure JavaScript will look like:
function add(start, end) {
var total = 0,
inputs = document.getElementsByClassName("myInput");
for (var i = start; i < Math.min(end, inputs.length); i++) [
total += +inputs[i].value;
});
return total;
}
Try
function calcTotal(index) {
var total = 0;
for (var i = 0; i < 9; i++) {
total += inputVals[index + i];
}
return total;
}
var total1 = calcTotal(0);
OR
function calcRangeTotal(index, count) {
var total = 0;
for (var i = 0; i < count; i++) {
total += inputVals[index + i];
}
return total;
}
var total1 = calcRangeTotal(0, 9);
Look at this:
var calculate = function() {
var sum=0;
$("input").each(function(index,element){
sum+=Number($(element).val());
});
alert(sum);
};
$(function(){
$("button").on("click",calculate);
});
Here is th jsFiddle.
var sum = 0;
function caluculate(firstIndex,secondIndex){
for(var i=one;i<secondIndex;i+=8)
sum=parseInt(sum+inputVals[i]);
}
function addarray($start,$end) {
var total = 0;
for(var i = $start; i < $end; i++)
total += inputVals[i];
return total;
}
var myTotal = addarray(9,17);

Categories

Resources