Javascript/HTML random character placed at bottom of page [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Random Character example Is a link to a picture of my web page.
I can't find the location where the > symbol at the bottom of the page is generated. I've used cmd f to search the code for a random one and none seem to be misplaced. It's not very intrusive, nonetheless, I like to understand my code.
Also, I do not understand why my for loop is not activating.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The web site of matt9878</title>
<!-- The style.css file allows you to change the look of your web pages.
If you include the next line in all your web pages, they will all share the same look.
This makes it easier to make new pages for your site. -->
<link href="/style.css" rel="stylesheet" type="text/css" media="all">
</head>
<body>
<div class="outputText">
<!-- Equations assighment -->
<p id="equation"> Equation assighment: <br/></p>
<!-- Counting Coins assighment -->
<p id="combinations"> Coin combo assighment: <br/></p>
<!-- Timely Mesasurements assighment -->
<p id= "circumference"> Timely Mesasurements assighment: <br/></p>
<!-- Blackjack assighment -->
<p id="blackjackTotal"> Blackjack assighment: <br/></p>
<!-- Prime Time Assighment -->
<p id="primeTime"> Prime Time assighment: <br/></p>
</div>
<!-- Greetings assignment -->
<script>
window.alert("Hola, Como esta?");
</script>
<!--Equations assighment-->
<script>
for(i = 0; i < 4; i++)
{
var x = Math.round(Math.random() * 1500);
var y = Math.round(Math.random() * 1500);
document.getElementById("equation").innerHTML += x + " + " + y + " = " + (x + y) + "<br/>";
}
//*seriesOfEquations();
</script>
<!-- Counting Coins assighment -->
<script>
var value = 175;
var penny = 1;
var nickel = 5;
var dime = 10;
var quarter = 25;
document.getElementById("combinations").innerHTML += (value / penny) + "(" + penny + ")" + " = " + value + "<br/>";
document.getElementById("combinations").innerHTML += (value / nickel) + "(" + nickel + ")" + " = " + value + "<br/>";
document.getElementById("combinations").innerHTML += Math.floor(value / dime) + "(" + dime + ")" +
" + " + nickel + " = " + value + "<br/>";
document.getElementById("combinations").innerHTML += (value / quarter) + "(" + quarter + ")" + " = " + value + "<br/>";
</script>
<!-- Timely Mesasurements assighment -->
<script>
var date = new Date();
var rad = date.getHours();
document.getElementById("circumference").innerHTML += (2 * Math.PI * rad).toFixed(3) + "<br/>";
</script>
<!-- Blackjack assighment -->>
<script>
//Card dealing
var cardOne = (Math.ceil(Math.random() * 10 ) + 1);
var cardTwo = (Math.ceil(Math.random() * 10 ) + 1);
var combined = cardOne + cardTwo;
var cardValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
//Ace checking
if (cardOne == 11 && combined > 21) {
cardOne = 1;
combined = cardOne + cardTwo;
}
else if (cardTwo == 11 && combined > 21) {
cardTwo = 1;
combined = cardOne + cardTwo;
}
//Dealer hit sequence
if (combined < 17) {
document.getElementById("blackjackTotal").innerHTML += "The dealer is hitting thier current total of " + combined + "<br/>";
cardOne = (Math.ceil(Math.random() * 10 ) + 1);
//Ace checking
if (cardOne == 11 && (combined + cardOne) > 21) {
cardOne = 1;
combined = combined + cardOne;
}
else {
combined = combined + cardOne;
}
}
//Blackjack
if (combined == 21) {
document.getElementById("blackjackTotal").innerHTML += "Blackjack!!!!" + "<br/>";
}
//Dealer bust
else if (combined > 21) {
document.getElementById("blackjackTotal").innerHTML += "The dealer has gone bust with a total of " + combined + "." + "<br/>";
}
//Dealer total ancouncement
else{
document.getElementById("blackjackTotal").innerHTML += "The dealer's total is " + combined + "." + "<br/>";
}
</script>
<!-- Prime time assighment -->
<script>
var numOne = Number(prompt("Please enter the first whole number to begin the range you'd like to explore."));
var numTwo = Number(prompt("Enter the second whole number to conclude the range you'd like to explore. Hint: Second choice > first."));
window.alert(numOne + ", " + numTwo);
if (numOne < numTwo && (numOne.isInteger() && numTwo.isInteger())) {
for(; numOne <= numTwo; numOne++) {
document.getElementById("primeTime").innerHTML += numOne + ", " + numTwo + "<br/>";
}
}
else {
window.alert("Please reload the webpage and try again. Error code: User error.");
}
</script>
</body>
</html>

In line 77 there was an extra > in a comment:
<!-- Blackjack assighment -->>
Which runs as
>
Fixed:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The web site of matt9878</title>
<!-- The style.css file allows you to change the look of your web pages.
If you include the next line in all your web pages, they will all share the same look.
This makes it easier to make new pages for your site. -->
<link href="/style.css" rel="stylesheet" type="text/css" media="all">
</head>
<body>
<div class="outputText">
<!-- Equations assighment -->
<p id="equation"> Equation assighment: <br/></p>
<!-- Counting Coins assighment -->
<p id="combinations"> Coin combo assighment: <br/></p>
<!-- Timely Mesasurements assighment -->
<p id= "circumference"> Timely Mesasurements assighment: <br/></p>
<!-- Blackjack assighment -->
<p id="blackjackTotal"> Blackjack assighment: <br/></p>
<!-- Prime Time Assighment -->
<p id="primeTime"> Prime Time assighment: <br/></p>
</div>
<!-- Greetings assignment -->
<script>
window.alert("Hola, Como esta?");
</script>
<!--Equations assighment-->
<script>
for(i = 0; i < 4; i++)
{
var x = Math.round(Math.random() * 1500);
var y = Math.round(Math.random() * 1500);
document.getElementById("equation").innerHTML += x + " + " + y + " = " + (x + y) + "<br/>";
}
//*seriesOfEquations();
</script>
<!-- Counting Coins assighment -->
<script>
var value = 175;
var penny = 1;
var nickel = 5;
var dime = 10;
var quarter = 25;
document.getElementById("combinations").innerHTML += (value / penny) + "(" + penny + ")" + " = " + value + "<br/>";
document.getElementById("combinations").innerHTML += (value / nickel) + "(" + nickel + ")" + " = " + value + "<br/>";
document.getElementById("combinations").innerHTML += Math.floor(value / dime) + "(" + dime + ")" +
" + " + nickel + " = " + value + "<br/>";
document.getElementById("combinations").innerHTML += (value / quarter) + "(" + quarter + ")" + " = " + value + "<br/>";
</script>
<!-- Timely Mesasurements assighment -->
<script>
var date = new Date();
var rad = date.getHours();
document.getElementById("circumference").innerHTML += (2 * Math.PI * rad).toFixed(3) + "<br/>";
</script>
<!-- Blackjack assighment -->
<script>
//Card dealing
var cardOne = (Math.ceil(Math.random() * 10 ) + 1);
var cardTwo = (Math.ceil(Math.random() * 10 ) + 1);
var combined = cardOne + cardTwo;
var cardValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
//Ace checking
if (cardOne == 11 && combined > 21) {
cardOne = 1;
combined = cardOne + cardTwo;
}
else if (cardTwo == 11 && combined > 21) {
cardTwo = 1;
combined = cardOne + cardTwo;
}
//Dealer hit sequence
if (combined < 17) {
document.getElementById("blackjackTotal").innerHTML += "The dealer is hitting thier current total of " + combined + "<br/>";
cardOne = (Math.ceil(Math.random() * 10 ) + 1);
//Ace checking
if (cardOne == 11 && (combined + cardOne) > 21) {
cardOne = 1;
combined = combined + cardOne;
}
else {
combined = combined + cardOne;
}
}
//Blackjack
if (combined == 21) {
document.getElementById("blackjackTotal").innerHTML += "Blackjack!!!!" + "<br/>";
}
//Dealer bust
else if (combined > 21) {
document.getElementById("blackjackTotal").innerHTML += "The dealer has gone bust with a total of " + combined + "." + "<br/>";
}
//Dealer total ancouncement
else{
document.getElementById("blackjackTotal").innerHTML += "The dealer's total is " + combined + "." + "<br/>";
}
</script>
<!-- Prime time assighment -->
<script>
var numOne = Number(prompt("Please enter the first whole number to begin the range you'd like to explore."));
var numTwo = Number(prompt("Enter the second whole number to conclude the range you'd like to explore. Hint: Second choice > first."));
window.alert(numOne + ", " + numTwo);
if (numOne < numTwo && (numOne.isInteger() && numTwo.isInteger())) {
for(; numOne <= numTwo; numOne++) {
document.getElementById("primeTime").innerHTML += numOne + ", " + numTwo + "<br/>";
}
}
else {
window.alert("Please reload the webpage and try again. Error code: User error.");
}
</script>
</body>
</html>

just above card dealing code, there is extra '>' in commented blackjack assignment. Hope it will help

Related

How do I fix this code regarding getelementbyid [Javascript]?

So I'm currently taking a coding class and am not very well versed in coding. I'm having trouble with a getelementbyid block which isn't writing my looped array for an assignment. Could anyone help me out?
Here's the code:
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById(message).innerHTML = "your name is " + input[n] + "<br>"
document.getElementById(message2).innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
Your variables and your id-s have the same names. By doing getElementbyId(message) you are passing the variables' values instead of the fixed id you gave to your elements.
You need to put the id-s in quotes as follows:
document.getElementById("message")
document.getElementById("message2")
Tested at my end and this is working code
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById('message').innerHTML = "your name is " + input[n] + "<br>"
document.getElementById('message2').innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
error:-
The id of getElementbyId must be in quotes
Make sure your selectors are strings
document.getElementById("message"); not document.getElementById(message);
Make sure you end your lines of code with semi-colons. This is not optional even though the code will attempt to run without them.
Change your output to render your accumulated data - right now you're overwriting your output every time you loop.
Note: I don't know what you're doing with the numerical value inside of the prompt methods (names and grade ) so I didn't touch it.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = [];
var message = " ";
var message2 = " ";
var n = 0;
var i = 1;
var names = n;
var grade = i;
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name " + names)
message += "Your name is " + input[n] + "<br>";
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value) " + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>";
}
document.getElementById("message").innerHTML = message + "<br>";
document.getElementById("message2").innerHTML = message2 + "<br>";
</script>
#SlavicMilk
Below should be sufficient for your assignment:
HTML (index.html):
<h1 style="text-align: center">Name and Grades</h1>
<table>
<thead>
<th>Name</th>
<th>Grade</th>
</thead>
<tbody id="data">
</tbody>
</table>
<script src="script.js"></script>
JS (script.js):
let student = []
for (let i = 0; i < 5; i++) {
student[i] = {
"name": window.prompt(`Enter Name ${i + 1}`),
"grade": window.prompt(`Enter Grade (numerical value) ${i + 1}`)
}
}
document.getElementById('data').innerHTML = student.map(student => {
return `<tr><td>${student.name}</td><td>${student.grade}</td></tr>`
})

vars not holding proper value after localStorage.getItem('key')

My code works fine up until I try to save my data, exit out, then reopen then load saved data. I save using localStorage.setItem('key', value) then I load using localStorage.getItem('key'), but after I load my vars are not holding the right values. Is localStorage.getItem('key') returning a string, because 1 +1 = 2, not 11 like it's displaying. please help.
The page itself is stored on my PC not online, I'm opening it up with Google Chrome. I run Windows Edge. When I try opening this with Internet Explorer, forget about localStorage.set/getItem all together. I've tried just running my code with the variables then try to save and load. (note:All my code works flawlessly until I try to save the variables, then reload them). I'm working on a video game so I need to be able to save my variables. And since I'm not sure where the problem in my code lies, I'm sorry but I see no other option than to post about 180 lines of code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="black" >
<font color="white" >
<progress id="myProgress" value="10" max="10"></progress><br>
<p id='demo5' ;></p>
<button id="enemy" type="button" onclick="dealDamage(), imageSwap()"><img
id="enemy1" src="Game_Images/smiley_1.png"></button>
<button id="spriteTest" type="button" onclick="imageSwap2()"><img
id="enemy2" src="Game_Images/smiley_1.png"></button><br>
<button id="upgrade" type="button" onclick="upgradeClickDamage()">
</button>
<button type="button" onclick="moreGold()">More Gold</button><br>
<button type="button" onclick="saveGame()">Save Game</button>
<button type="button" onclick="loadGame()">Load Game</button>
<p id='demo' ;></p>
<p id='demo2' ;></p>
<p id='demo3' ;></p>
<p id='demo4' ;></p>
<script>
var clickDamage = 1;
var gold = 0;
var stage = 1;
var enemyNum = 1;
var enemiesTotal = 10;
var enemiesKilled = 0;
var cost = 100;
var enemyHPTotal = 10;
var enemyHPCurrent = 10;
document.getElementById("upgrade").innerHTML = "Upgrade click damage for:"
+ cost + " gold.";
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
document.getElementById("demo3").innerHTML = "Enemies Killed This Stage:"
+ enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:" +
enemyHPCurrent + "/" + enemyHPTotal;
function imageSwap() {
var image = document.getElementById("enemy1");
if (image.src.match("Game_Images/smiley_1")){
image.src="Game_Images/smiley_2.png"
}
else if (image.src.match("Game_Images/smiley_2")){
image.src="Game_Images/smiley_3.png"
}
else {
image.src="Game_Images/smiley_1.png"
}
}
function imageSwap2(){
var image2 = document.getElementById("enemy2");
if(image2.src.match("Game_Images/smiley_1")){
setTimeout(image2.src="Game_Images/smiley_2.png", 300);
}
else if(image2.src.match("Game_Images/smiley_2")){
setTimeout(image2.src="Game_Images/smiley_3.png", 300);
}
else {
setTimeout(image2.src="Game_Images/smiley_1.png", 300);
}
}
function dealDamage() {
document.getElementById("myProgress").value -= clickDamage;
//If enemy is hit but does not die
if(document.getElementById("myProgress").value >= 1){
enemyHPCurrent = document.getElementById("myProgress").value
enemyHPTotal = document.getElementById("myProgress").max
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
//If enemy is killed and there are remaining enemies in the current stage
if (document.getElementById("myProgress").value == 0 && enemyNum < 10) {
document.getElementById("myProgress").value =
document.getElementById("myProgress").max;
gold += (1 * stage);
enemyHPTotal = document.getElementById("myProgress").value;
enemyNum += 1;
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
enemiesKilled += 1;
document.getElementById("demo3").innerHTML = "Enemies Killed This
Stage:" + enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
enemyHPCurrent = enemyHPTotal;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
//If the enemy is killed and it is the last enemy of the current stage
if (document.getElementById("myProgress").value == 0 && enemyNum == 10) {
document.getElementById("myProgress").max += 1;
document.getElementById("myProgress").value =
document.getElementById("myProgress").max;
gold += (1 * stage);
enemyNum = 1;
stage += 1;
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
enemiesKilled = 0;
document.getElementById("demo3").innerHTML = "Enemies Killed This
Stage:" + enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
enemyHPTotal = document.getElementById("myProgress").max;
enemyHPCurrent = enemyHPTotal;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
}
function upgradeClickDamage() {
if (gold >= cost) {
gold -= cost;
clickDamage += 1;
cost += 100;
document.getElementById("messageBox").innerHTML =
"Congratulations!!! You just upgraded your click damage."
document.getElementById("upgrade").innerHTML = "Upgrade click damage
for:" + cost + " gold.";
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
}
else if (gold < cost) {
document.getElementById("messageBox").innerHTML = "You don't have
enough gold for this upgrade."
}
}
function moreGold() {
gold += 100;
document.getElementById("demo").innerHTML = "Gold: " + gold;
}
function saveGame(){
//save all vars
localStorage.setItem('CLICKDAMAGE', clickDamage);
localStorage.setItem('GOLD', gold);
localStorage.setItem('STAGE', stage);
localStorage.setItem('ENEMYNUM', enemyNum);
localStorage.setItem('ENEMIESTOTAL', enemiesTotal);
localStorage.setItem('ENEMIESKILLED', enemiesKilled);
localStorage.setItem('COST', cost);
localStorage.setItem('ENEMYHPTOTAL', enemyHPTotal);
localStorage.setItem('ENEMYHPCURRENT', enemyHPCurrent);
}
function loadGame(){
//load all vars
clickDamage = localStorage.getItem('CLICKDAMAGE');
gold = localStorage.getItem('GOLD');
stage = localStorage.getItem('STAGE');
enemyNum = localStorage.getItem('ENEMYNUM');
enemiesTotal = localStorage.getItem('ENEMIESTOTAL');
enemiesKilled = localStorage.getItem('ENEMIESKILLED');
cost = localStorage.getItem('COST');
enemyHPTotal = localStorage.getItem('ENEMYHPTOTAL');
enemyHPCurrent = localStorage.getItem('ENEMYHPCURRENT');
}
</script>
<div id="messageBox"></div>
</font>
</body>
</html>
I expected all variables to function properly after loading.
gold, cost, and enemiesKilled are all affected by this same problem. If gold = 1, and I save that variable then load that variable later, then add 1 again, I get 11, not 2. With cost, if cost = 100, then I save, then I load later, then I add 100 to cost, cost = 100100 not 200.
(This will restate a bit of what you hypothesized in your question for the sake of completeness)
If you look at the documentation for Storage.getItem(), it says:
Return value
A DOMString containing the value of the key. If the key does not exist, null is returned.
This means that no matter what data type you give in setItem, the output of getItem will always be a string. This is easy to test in the console:
localStorage.setItem("test", 1);
> undefined
localStorage.getItem("test");
> "1"
When you add a string to a number, it just concatenates the two together. In your case, you're adding "1" + 1 which becomes "11" instead of adding 1 + 1 which would be 2. The solution is to convert the number string into a number, which can be done several ways, but is easiest to do (in my opinion) by simply prefixing the expression with a +.
+localStorage.getItem("test");
> 1
The localStorage.setItem converts all passed values to string. Once you call localStorage.getItem you are getting back string value.
So you are trying to concatenate string and number "1" + 1 === "11".
To prevent this behavior you need to manually convert values to stringified JSON:
localStorage.setItem('CLICKDAMAGE', JSON.stringify(clickDamage));
And then parse it back:
clickDamage = JSON.parse(localStorage.getItem('CLICKDAMAGE'));

how to declare div and id/class in java script

I have the index.html file in that form fields are there form action is confirm.html. In confirm.html some data, I displayed using js. But showing the only table I decided to I use menus in that so more attractive for users. Whenever I'm trying to declare div(<h1>data</h1>) in confirm.html it won't be showing any data. so I decided to declare using js.
Top of the headers i have to show those menus:
document.write("<div class="Menu">");
document.write("<div class="leftmenu">");
document.write("<h4>Fegli</h4>");
document.write("<div class="Menu">");
doucment.write("<ul>");
document.write("<li>Home</li>");
document.write("</ul>");
document.write("</div>");
document.write("</div>");
document.write("</div>");
Confirm.html: code
<html>
<head>
<script type="text/javascript" src="calculate.js">
</script>
</head>
<body onload="init();">
<div id="Menu">
it wont showing on web page
</div>
</body>
</html>
Calculate.js code
// Called on body's `onload` event
var cumulative=0;
function init() {
var salary = parseInt(localStorage.getItem("salary"));
var percent = parseFloat(localStorage.getItem("percent"));
var age = parseInt(localStorage.getItem("age"));
var rAge = parseInt(localStorage.getItem("rAge"));
var sel = localStorage.getItem("sel");
var roundedSalary = parseInt(Math.ceil((salary + 2000) / 1000) * 1000); //Doing Rounding for basic column Display
var basic;
var factor = 0;
var biWeekly = 0, monthly = 0,annual = 0;
//Displaying Headers
document.write("<head>");
document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"confirm.css\">");
document.write("<title>Result</title>");
document.write("</head>");
document.write("<body>");
/* document.write("<center>")
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
document.write("<h1>" + "FEGLI CALCULATIONS ON" + " " + today + "</h1>");
document.write("</center>")
*/
document.write("<table><tr><th> Age </th><th> Annual-Salary </th><th> BiWeekly-Premium </th><th> Monthly-Premium </th><th> Annual-Premium </th><th> Cumulative-Premium </th><th>Basic </th><th> Total </th></tr>");
basic = parseInt(roundedSalary * calculateFactor(age));
//document.write("roundedSalary"+roundedSalary+"calculateFactor"+calculateFactor(age));
premium = calculateBiweekly(salary, basic, age, rAge);
biWeekly = premium[0];
monthly = premium[1];
annual = premium[2];
cumulative = premium[3];
document.write("<tr><td>" + age + "/" + (age + 1) + "</td><td>" + "$" + salary.toFixed(2) + "</td><td>" + "$" + biWeekly.toFixed(2) + "</td><td>" + "$" + monthly.toFixed(2) + "</td><td>" + "$" + annual.toFixed(2) + "</td><td>" + "$" + cumulative.toFixed(2) + "</td><td>" + "$" + basic + "</td><td>-</td></tr>");
salary = parseFloat(salary);
for (var i = age + 1; i < 101; i++) {
document.write("<tr>");
document.write("<td>" + i + "/" + (i + 1) + "</td>");
if (i < rAge) {
salary = salary + (salary * percent);
roundedSalary = parseInt(Math.ceil((salary + 2000) / 1000) * 1000);
// document.write("age"+i+"roundedSalary"+roundedSalary+"<br>");
document.write("<td>" + "$" + salary.toFixed(2) + "</td>");
} else {
salary = 0;
document.write("<td>-</td>");
}
basic = parseInt(roundedSalary * calculateFactor(i));
premium = calculateBiweekly(salary, basic, i);
biWeekly = premium[0];
monthly = premium[1];
annual = premium[2];
cumulative = premium[3];
document.write("<td>" + "$" + biWeekly.toFixed(2) + "</td>");
document.write("<td>" + "$" + monthly.toFixed(2) + "</td>");
document.write("<td>" + "$" + annual.toFixed(2) + "</td>");
document.write("<td>" + "$" + cumulative.toFixed(2) + "</td>");
document.write("<td>" + "$" + basic + "</td>");
document.write("<td>-</td>");
document.write("</tr>");
}
document.write("</table>");
document.write("</body>")
}
function calculateFactor(age) {
var factor = 0;
if (age > 35 && age < 45) {
switch (age) {
case 36:
factor = 1.9;
break;
case 37:
factor = 1.8;
break;
case 38:
factor = 1.7;
break;
case 39:
factor = 1.6;
break;
case 40:
factor = 1.5;
break;
case 41:
factor = 1.4;
break;
case 42:
factor = 1.3;
break;
case 43:
factor = 1.2;
break;
case 44:
factor = 1.1;
break;
}
} else if (age <= 35) {
factor = 2;
} else if (age >= 45) {
factor = 1;
}
return factor;
}
function calculateBiweekly(salary, basic, age) {
var biWeekly = 0;
if (salary > 0) {
biWeekly = ((basic / calculateFactor(age)) * 0.15) / 1000;
monthly = ((basic / calculateFactor(age)) * 0.325) / 1000;
} else if (salary == 0 && age <= 65) {
biWeekly = ((basic / calculateFactor(age)) * (2.455 / 2.166)) / 1000;
monthly = ((basic / calculateFactor(age)) * (2.455)) / 1000;
} else if (salary == 0 && age > 65) {
//document.write("age"+age+"salary"+salary+"<br>");
biWeekly = ((basic / calculateFactor(age)) * (2.13 / 2.166)) / 1000;
monthly = ((basic / calculateFactor(age)) * (2.13)) / 1000;
}
annual = 12 * monthly;
cumulative = cumulative+annual;
//document.write("cumulative"+cumulative+"<br>");
return [biWeekly, monthly, annual, cumulative];
}// Called on body's `onload` event
I don't recommend document.write() to create element in DOM.
You need to use document.createElement() function to create new element using javascript.
function addMenu() {
var html = '<div class="Menu">';
html += '<div class="leftmenu">';
html += '<h4>Fegli</h4>';
html += '<div class="Menu">';
html += '<ul><li>Home</li></ul>';
html += '</div>';
html += '</div>';
html += '</div>';
document.getElementById("Menu").innerHTML = html;
}
addMenu();
<div id="Menu"></div>
In your code you applied table using document.write(), you can also create table tag using document.createElement() function. check below examples:
Example 1 :
function addTable() {
var c, r, t;
t = document.createElement('table');
t.border=1;
r = t.insertRow(0);//create row
c = r.insertCell(0);///create cell
c.innerHTML = "Apple";
c = r.insertCell(1);///create second cell
c.innerHTML = "Orange";
document.getElementById("mainContainer").appendChild(t);
}
addTable();
<div id="mainContainer"></div>
Example 2 :
function addTable() {
var html = "<table border='1'><tr><td>Apple</td><td>Orange</td></tr></table>";
document.getElementById("mainContainer").innerHTML = html;
}
addTable();
<div id="mainContainer"></div>
Both example will give same result.

How to use Documet.write to print to browser

I am beginner at java script. I am trying to write a script that prompts the users to enter 3 numbers and the program count the number of zero, positive and negative integers user inserted. However,When I output to browser, there is not output shown to browser.
here is my Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Counter</title>
<script type="text/javascript">
<!--
var zero =0;
var negative =0;
var positve =0;
var a1 = ["first", "second", "third", "fourth"];
var a2 = [];
var i = 0;
for( x=0; x< a1.length; x++){
a2. push (prompt("Enter " + a1[x]+ " integer\n" + ""));
}
while (i < a2.length)
{
if (a2[i++]== 0)
zero = zero + 1;
else if (a2[i++] < 0)
negative = negative + 1;
else
{
positive = positive + 1;
i ++;
}
}
//-->
</script>
</head>
<body>
<h1> Welcome to Counter System </h1>
<script>
<!--
document.write ("Zeros Numbers entered by the users = " + zero + " <br/>" +
"Positive Numbers entered by the users= " + positive + "<br/> "+
"Negative Numbers entered by the users =" + negative + "<br/>");
//-->
</script>
</body>
I guess the values are not getting printed as they are not present in below script tag as script tags get differentiated on run time. You can do like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Counter</title>
<script type="text/javascript">
<!--
var zero =0;
var negative =0;
var positve =0;
var a1 = ["first", "second", "third", "fourth"];
var a2 = [];
var i = 0;
for( x=0; x< a1.length; x++){
a2. push (prompt("Enter " + a1[x]+ " integer\n" + ""));
}
while (i < a2.length)
{
if (a2[i++]== 0)
zero = zero + 1;
else if (a2[i++] < 0)
negative = negative + 1;
else
{
positive = positive + 1;
i ++;
}
}
<!--
document.write ("Zeros Numbers entered by the users = " + zero + " <br/>" +
"Positive Numbers entered by the users= " + positive + "<br/> "+
"Negative Numbers entered by the users =" + negative + "<br/>");
//-->
//-->
</script>
</head>
<body>
<h1> Welcome to Counter System </h1>

Random Number Generator Javascript - Ranges

Looking for some guidance from those more knowledgeable than myself.
I'm writing a program that will prompt the user to click a button, which will then generate a random integer from 1 to 100.
I can manage that part fine. What I am struggling with is making the program print what range this random integer is in i.e. i<=33.
For example, when I click the button I want to see:
"10 is a number less than 33"
or
"55 is a number between 33 and 66"
Here is my code so far, I have put the code I am having problems with in comments.
<!DOCTYPE HTML5>
<html>
<head>
<meta charset="UTF-8">
<title>question2</title>
</head>
<body>
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i = Math.floor((Math.random() * 100) + 1);
document.getElementById("demo").innerHTML = i;
}
// if (myFunction <= 33) {
// text += ("<br>" + i + " is a number less than or equal to 33");
// }
// if (myFunction > 34 and i < 65) {
// text += ("<br>" + i + " is a number between 33 and 66 (exclusive)");
// }
// if (my Function >= 66) {
// text += ("<br>" + i + " is a number greater than or equal to 66");
// }
</script>
</body>
</html>
Thanks guys.
You could test and if true display the result and exit.
function getRandom() {
var i = Math.floor((Math.random() * 100) + 1);
if (i <= 33) {
document.getElementById("demo").innerHTML += i + " is a number less than or equal to 33<br>";
return;
}
if (i < 66) {
document.getElementById("demo").innerHTML += i + " is a number between 33 and 66 (exclusive)<br>";
return;
}
document.getElementById("demo").innerHTML += i + " is a number greater than or equal to 66<br>";
}
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="getRandom()">Click here</button>
<p id="demo"></p>
Did you mean something like this:
function myFunction() {
var text = "";
var i = Math.floor((Math.random() * 100) + 1);
if (i <= 33) {
text += ("<br>" + i + " is a number less than or equal to 33");
}
if (i > 34 && i < 65) {
text += ("<br>" + i + " is a number between 33 and 66 (exclusive)");
}
if (i >= 66) {
text += ("<br>" + i + " is a number greater than or equal to 66");
}
document.getElementById("demo").innerHTML = text;
}
The problem is you are calling variables from inside myFunction() outside of that function. Examples include i and myFunction(). It would be better to put the if else statements inside the main function.
function myFunction() {
var demo = document.getElementById("demo");
var i = Math.floor((Math.random() * 100) + 1);
if (i <= 33) {
demo.innerHTML = i + " is a number less than 33";
}
else if (i < 65) {
demo.innerHTML = i + "is a number between 33 and 65";
}
else {
demo.innerHTML = i + " is a number greater than or equal to 66";
}
}
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
Your function isn't what you should be comparing against in your if statements.
But, I did throw something together let me know if this is what you were looking for.
You were on the right track. Also on the middle comparison I changed you "and" to a shortcircuit "&&".
JSfiddle: https://jsfiddle.net/xew8dvbd/
$(document).ready(function() {
function myFunction() {
var i = Math.floor((Math.random() * 100) + 1);
var text = "";
if (i <= 33) {
text += ("<br>" + i + " is a number less than or equal to 33");
}
if (i > 34 && i < 65) {
text += ("<br>" + i + " is a number between 33 and 66 (exclusive)");
}
if (i >= 66) {
text += ("<br>" + i + " is a number greater than or equal to 66");
}
document.getElementById("demo").innerHTML = text;
};
$("#submit").click(myFunction);
});
Not sure why, but I had to do this as a function expression rather than a function definition to make it work. Oddly, that's the second time this one worked as a gotcha in the last hour.
myFunction = function() {
var text = "";
var i = Math.floor((Math.random() * 100) + 1);
document.getElementById("demo").innerHTML = i;
switch (true) {
case (i < 20):
console.log(i + " is less than 20.");
break;
case (i < 40):
console.log(i + " is between 21 and 40.");
break;
case (i < 60):
console.log(i+ " is between 21 and 60.");
break;
default:
console.log(i+ " is over 60.");
}
};
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>

Categories

Resources