Calculating a student grade in JavaScript - javascript

I've got an HTMl form to input student names and grades in which should use JavaScript to calculate a grade that is then printed on the screen. My HTMl works fine if I comment the meat of my JavaScript out, but not if I don't. The error is somewhere in the code that I commented out, but I just can't find it (or them).
The HTML form will submit, alert the user, and show my message correctly as long as it is fed a concrete grade and score instead of trying to fetch it through getGrade() and getScore(). This is why I know the bug is in the JavaScript.
I've run the page in the JavaScript console to look for bugs, but there are no red flag errors.
This is my first HTML/JavaScript program, and I not very good at it. Anyway, it's a day late and in less than two hours, it will be two days late, so if anyone could help, I'd appreciate it hugely. Here's the code, sorry if it's too much:
<!DOCTYPE html>
<html>
<head>
<title>Joe Peterson's Assignment 7</title>
<script>
function calculateGrade(){
document.getElementById("form1").style.display = "none";
document.getElementById("p1").style.display = "block";
var fname = document.getElementById("LastName").value;
var lname = document.getElementById("FirstName").value;
var valMidterm = document.getElementById("MidtermScore").value;
var valFinal = document.getElementById("FinalScore").value;
var lMidterm = document.getElementById("MidtermLetter").value;
var lFinal = document.getElementById("FinalLetter").value;
var homeworkArray = document.getElementById("HomeworkScores").value.split(',');
var classworkArray = document.getElementById("ActivityScores").value.split(',');
/*
var s1 = new Student(fname, lname);
for (var i = 0; i < classworkArray.length; i++)
s1.addGradedActivity(classworkArray[i]);
for (var i = 0; i < homeworkArray.length; i++)
s1.addGradedHomework(homeworkArray[i]);
s1.setMidterm(valMidterm, lMidterm);
s1.setFinal(valFinal, lFinal);
var grade = s1.getGrade();
var score = s1.getScore();
*/
document.getElementById("span1").innerHTML = (grade);
document.getElementById("span2").innerHTML = (score);
document.getElementById("fname").innerHTML = (fname);
document.getElementById("lname").innerHTML = (lname);
alert(document.getElementById("FirstName").value);
return false;
}
/*
function Coursework(){
var sum = 0;
var num = 0;
this.addScore = function(score){
if (score < 0) {score = 0;}
if (score > 100) {score = 100;}
sum += score;
num++;
}
this.getAverage = function(){
return (sum/num);
}
}
function Exam(){
var score = 0;
var grade = "";
this.Exam = function(Score, Grade)
{
if (Score < 0) {Score = 0;}
if (Score > 100) {Score = 100;}
score = Score;
if (Grade != "A" && Grade != "B" && Grade !="C"
&& Grade !="D" && Grade != "F")
{
console.log("You have submitted a bad grade for an Exam, value of:G.");
Grade = "F";
}
grade = Grade;
}
this.getScore = function(){
return score;
}
this.getGrade = function(){
return grade;
}
}
function Student(){
var firstName;
var lastName;
var midterm;
var finalExam;
var homework = new Coursework();
var inclass = new Coursework();
this.Student = function(first, last){
firstName = first;
lastName = last;
}
this.setMidterm = function(score, grade){
midterm = new Exam(score, grade);
}
this.setFinal = function(score, grade){
finalExam = new Exam(score, grade);
}
this.addGradedHomework = function(score){
homework.addScore(score);
}
this.addGradedActivity = function(score){
inclass.addScore(score);
}
this.getFinalGrade = function(totalScore)
{
var grade = totalGrade(totalScore);
var grade2 = "F";
var midGrade = this.convertGrade(midterm.getGrade());
var finGrade = this.convertGrade(finalExam.getGrade());
if (midGrade < finGrade)
{
grade2 = midterm.getGrade();
}
else
{
grade2 = finalExam.getGrade();
}
if (convertGrade(grade) > convertGrade(grade2))
return(grade);
else
return(grade2);
}
this.totalGrade = function(totalScore)
{
var totalGrade = "F";
if (totalScore >= 90)
totalGrade = "A";
else if (totalScore >= 80)
totalGrade = "B";
else if (totalScore >= 70)
totalGrade = "C";
else if (totalScore >= 60)
totalGrade = "D";
else
totalGrade = "F";
return (totalGrade);
}
this.convertGrade = function(letter)
{
var num = 0;
if (letter === "A")
num = 4;
else if (letter === "B")
num = 3;
else if (letter === "C")
num = 2;
else if (letter === "D")
num = 1;
else
num = 0;
return(num);
}
this.getScore = function()
{
var totalScore = 0;
totalScore += inclass.getAverage() * .15;
totalScore += homework.getAverage() * .25;
totalScore += midterm.getScore() * .25;
totalScore += finalExam.getScore() * .35;
return totalScore;
}
this.getGrade = function()
{
var totalScore = 0;
totalScore += inclass.getAverage() * .15;
totalScore += homework.getAverage() * .25;
totalScore += midterm.getScore() * .25;
totalScore += finalExam.getScore() * .35;
var grade = getFinalGrade(totalScore);
return grade;
}
}
*/
</script>
</head>
<body>
<p><h1>Joe Peterson's Assignment 7</h1></p>
<form name="input" id="form1" onsubmit="return calculateGrade()" style="display:form">
First name: <input type="text" name="FirstName" id="FirstName" value="Joe"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Peterson"><br>
Homework Scores (separate with commas): <input type="text" name="HomeworkScores" id="HomeworkScores" value="90, 80, 98"><br>
Activity Scores (separate with commas): <input type="text" name="ActivityScores" id="ActivityScores" value="71, 65, 96"><br>
Midterm Exam Percentage: <input type="text" name="MidtermScore" id="MidtermScore" value="91"><br>
Midterm Exam Letter Grade: <input type="text" name="MidtermLetter" id="MidtermLetter" value="A"><br>
Final Exam Percentage: <input type="text" name="FinalScore" id="FinalScore" value="75"><br>
Final Exam Letter Grade: <input type="text" name="FinalLetter" id="FinalLetter" value="C"><br>
<input type="submit" value="Submit">
</form>
<p id="p1" style="display:none">Final course grade for <span id="fname">Joe</span> <span id="lname">Peterson</span> is: <span id="span1">X</span> (<span id="span2">yy</span>%)</p>
</body>
</html>

Related

How to make value become 0 in textbox?

I am making a dice game where you roll dice. When you roll a number that number adds to your total score. But when you roll a 1 you lose your total score and it switches to the other player. You can also hold to switch player.
As it is right now it become 0 after getting a 1 the first time. My problem is that when you switch back to the original starter player the score that was there before comes back. Like it does not stay the value of 0 but only looks like it.
var swithcing = false;
var current1 = 0;
var total1 = 0;
var current2 = 0;
var total2 = 0;
function roll() {
var randomnumber = Math.floor(Math.random() * 6) + 1;
var player1score = document.querySelector('.player1total');
var player1curent = document.querySelector('.player1');
var player2score = document.querySelector('.player2total')
var player2curent = document.querySelector('.player2')
if (randomnumber == 1) {
swithcing = !swithcing;
player1score.innerHTML = 0;
player1curent.innerHTML = 0;
player2curent.innerHTML = 0;
}
if (randomnumber == 1 && swithcing == false) {
player2score.innerHTML = 0;
}
if (swithcing == true) {
current2 += randomnumber;
player2score.innerHTML = current2;
player2curent.innerHTML = randomnumber;
}
if (swithcing == false) {
current1 += randomnumber;
player1score.innerHTML = current1;
player1curent.innerHTML = randomnumber;
}
}
function hold() {
swithcing = !swithcing;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />
I think your code should look something like this
let switching = false;
let current1 = 0;
let total1 = 0;
let current2 = 0;
let total2 = 0;
let randomnumber = 0
const player1score = document.querySelector('.player1total');
const player1current = document.querySelector('.player1');
const player2score = document.querySelector('.player2total');
const player2current = document.querySelector('.player2');
function roll() {
randomnumber = Math.floor(Math.random() * 6) + 1;
//console.log(randomnumber);
//logic for normal rolls
if(randomnumber > 1){
if(switching==true){
current2=randomnumber;//set to number rolled
total2+=randomnumber;//sum to total score
} else {
current1=randomnumber;//set to number rolled
total1+=randomnumber;//sum to total score
}
}
//logic if player loses
if (randomnumber == 1) {
//switch
switching = !switching;
//if switches to player 2
current1=0;//reset
current2=0;//reset
if(switching==true){
//console.log("Player 2 selected");
total2+=total1//total becomes player 1 previous total
total1=0;//player 1 total resets
} else {
//console.log("Player 1 selected");
total1+=total2//total becomes player 2 previous total
total2=0;//player 2 total resets
}
}
player1score.textContent = total1;
player1current.textContent = current1;
player2current.textContent = current2;
player2score.textContent = total2;
}
function hold() {
switching = !switching;
player1score.textContent = total1;
player1current.textContent = 0;
player2current.textContent = 0;
player2score.textContent = total2;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />

return to zero after reach max value and add the remaining value javascript

sorry i am newbie here
i need some help,
this case like notice a time.
when real time passes input value, then span with id alertLabel will change.
the problem is, if input value plus with input with id Duration will exceed real minutes or hours.
this is my code example.
javascript.js
var alertLabel = document.getElementById("alertLabel");
var less = document.getElementById("lessThan").value.replace(":", "");
var late = document.getElementById("timeIn").value.replace(":", "");
var duration = parseInt(document.getElementById("Duration").value);
var outs = document.getElementById("timesOut").value.replace(":", "");
var lessInt = parseInt(less);
var lateInt = parseInt(late);
var outsInt = parseInt(outs);
var durationOut = outsInt + duration; // this will be exceed
var durationIn = lateInt + duration; // this will be exceed
function getAlert() {
let times = new Date();
let sh = times.getHours() + "";
let sm = times.getMinutes() + "";
let ss = times.getSeconds() + "";
let shLong = sh.length == 1 ? "0" + sh : sh;
let smLong = sm.length == 1 ? "0" + sm : sm;
let ssLong = ss.length == 1 ? "0" + ss : ss;
let shSm = shLong + smLong;
document.getElementById("clock").innerHTML = shLong + ":" + smLong + ":" + ssLong;
if (shSm >= outsInt && shSm < durationOut) {
alertLabel.innerHTML = "OUT!!";
} else if (shSm >= lessInt && shSm < lateInt) {
alertLabel.innerHTML = "hurry up, don't be late!!";
} else if (shSm >= lateInt && shSm < durationIn) {
alertLabel.innerHTML = "LATE!!";
} else {
if (shLong >= 21 || shLong <= 4) {
alertLabel.innerHTML = "good dream tonight !!";
} else if (shLong >= 5 && shLong <= 11) {
alertLabel.innerHTML = "spirit Morning !!";
} else if (shLong >= 12 && shLong <= 17) {
alertLabel.innerHTML = "happy Noon !!";
} else if (shLong >= 18 && shLong <= 20) {
alertLabel.innerHTML = "nice evening !!";
}
}
}
<!doctype html>
<html>
<head>
<title></title>
</head>
<body onload="getAlert();setInterval('getAlert()',1000)">
<span id="clock"></span>
<span id="alertLabel"></span>
<div></div>
<input class="" type="text" id="lessThan" value="13:45" name="lessThan"> <!-- when time to in is near -->
<input class="" type="text" id="timeIn" value="13:48" name="timeIn"> <!-- time in and get alert Late -->
<input type="text" id="timesOut" value="13:55" name="timesOut"> <!-- value time to out and get alert Out -->
<input type="text" name="Duration" id="Duration" value="5"> <!-- duration alert for id timeIn and timesOut if more than 100 is the problem, this input as minute -->
</body>
</html>
this is my last try, example in input id timeIn
var a = document.getElementById("timeIn").value.split(":");
for (var i = 0; i < duration; i++){
var b = parseInt(a[0]); // this for hours
var c = parseInt(a[1]); // this for minutes
var x = c + i;
if (x >= 60){
var n = b + 1;
x = x-60;
}
console.log(x);
}
in my last try, in log var x return to zero just once
and the question is, if input value with id duration more than 100, how looping, if each var x reach value (60) his return to zero and var c plus 1 each var x reach 60.
maybe anyone have an easier one to solve this case.
sorry if the explanation is unclear.

Javascript for loop not repeating strings

very new to Javascript here, and I think I'm having a logic issue. So basically for class I'm building a hangman game, and I am having trouble with double letters. for instance if the word is food, when I enter an "O" it will pass through the for loop, hit that first O, push it to the screen, and stop dead in its tracks. I can do whatever I want to that first "O" but a second one or any other repeated letter gets ignored. Now the alert I wrote directly under the start of the for() loop, will successfully print both "O's", as will logging it to the console, or even flat out writing document.write(splitWord[m]);
So to me, I think it has to be my if statement. I could be 100% wrong on this, but I assume that the if statement tells it to see the first "O", do what's in the bracket, and then move on to the next letter skipping any doubles. If I am right about this, what would be a better option to keep the loop going, so both "O's" would be filled. And if I am completely wrong, what would be a better course of action to accomplish this task. Any help would be very greatly appreciated.
Thanks
var remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var removedLetters =[];
var wordList = ["django", "the#good#the#bad#and#the#ugly", "a#fistful#of#dollars","for#a#few#dollars#more","once#upon#a#time#in#the#west","the#wild#bunch","pale#rider"];
var titleList =["django", "The Good The Bad And The Ugly", "A Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"];
var songList =["Jango", "The Good The Bad And The Ugly", "Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"]
var selectedWord;
console.log(selectedWord);
var livesRemaining = 12;
var score = 0;
var wordWorth = 0;
var wins = 0;
var losses = 0;
var gameOn = false;
function chooseAWord(){
selectedWord = wordList[Math.floor(Math.random() * wordList.length)];
console.log(selectedWord);
}
function printWord(){
document.getElementById("wordDisplayer").innerHTML = selectedWord;
}
function buildTiles(){
// create a new div element
// and give it some content
var splitWord = selectedWord.split("");
for(i = 0; i < splitWord.length; i++){
if (splitWord[i] != '#'){
// var newTile = document.createElement("div");
//var newContent = document.createTextNode("");
//newTile.appendChild(newContent); //add the text node to the newly created div.
document.getElementById("wordTiles").innerHTML += '<div class="tileStyle" id="' + splitWord[i] + '"></div>';
wordWorth++;
// add the newly created element and its content into the DOM
//var currentDiv = document.getElementById("wordTiles");
//currentDiv.appendChild(newTile, currentDiv);
// newTile.setAttribute("class", "tileStyle");
}else if(splitWord[i] == '#'){
var blankTile = document.createElement("div");
var spaceContent = document.createTextNode("");
blankTile.appendChild(spaceContent);
document.getElementById("wordTiles").innerHTML += '<div class="blankStyle" id="' + splitWord[i] + '"></div>';
}
}
}
function clearTiles(){
var myNode = document.getElementById("wordTiles");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
function refreshAlphabet(){
remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
displayAvailableLetters();
}
function keyPressed(){
checkPlayerChoiceNew();
}
var playerGuess = document.onkeyup = function myKeyDown(event){
playerGuess = event.key;
if(gameOn==true){
keyPressed();
}else{
}
}
function checkPlayerGuess(){
document.getElementById("isThisWorking").innerHTML = playerGuess;
}
// function myFunction() {
// var str = "Tha bast things in lifa ara free";
// var patt = new RegExp(playerGuess);
// var res = patt.test(selectedWord.toLowerCase());
// document.getElementById("demo").innerHTML = res;
//}
function displayAvailableLetters(){
document.getElementById("lettersStillAvailable").innerHTML = remainingLetters;
console.log(remainingLetters);
}
function displayRemovedLetters(){
document.getElementById("lettersUsed").innerHTML = removedLetters;
}
function updateScore(){
document.getElementById("scoreTotal").innerHTML = score;
}
function updateWins(){
document.getElementById("winTotals").innerHTML = wins;
}
function updateLosses(){
document.getElementById("lossTotals").innerHTML = losses;
}
function checkScore(){
if(score == selectedWord.length && livesRemaining > 0){
document.getElementById("gameOver").innerHTML = "WINNER! Congratulations!!!";
wins++;
updateWins();
gameOn=false;
}else if (livesRemaining == 0){
livesRemaining == -1;
document.getElementById("gameOver").innerHTML = "You have failed!";
losses++;
updateLosses();
gameOn=false;
}else{
document.getElementById("gameOver").innerHTML = "Good Luck!";
}
}
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = playerGuess;
}
}
}
//check playerGuess against selectedWord
function checkPlayerChoice(){
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
if(compareWord == true && compareAlphabet == true ){
document.getElementById("demo").innerHTML = playerGuess;
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
displayAvailableLetters();
displayRemovedLetters();
score++;
updateScore();
checkScore();
}else if(compareWord == true && compareAlphabet == false){
document.getElementById("demo").innerHTML = "Already tried that one";
}else if(compareWord == false && compareAlphabet == true){
livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
document.getElementById("demo").innerHTML = "Already tried that one ;)";
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
}else{
/*livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();*/
document.getElementById("demo").innerHTML = "Not a Valid Key";
}
}
//document.onkeyup = function myKeyDown(event){
// playerGuess = event.key;
//}
//start / Restart the game
function resetGame() {
livesRemaining = 12;
score =0;
wordWorth = 0;
clearTiles();
document.getElementById("lives").innerHTML = livesRemaining;
chooseAWord();
printWord();
buildTiles();
refreshAlphabet();
gameOn=true;
}
.tileStyle{
width:30px;
height:30px;
border:1px solid black;
background-color:green;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.blankStyle{
width:30px;
height:30px;
background-color:orange;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.fixer{
width:100%;
height:10px;
clear:both;
}
<body>
<button onclick="checkPlayerChoice()">Try it</button>
<p id="demo"></p>
<p> lives: </p>
<p id = "lives"> 0</p>
<p> Score: </p>
<p id = "scoreTotal">0</p>
<p>wins</p>
<p id ="winTotals">0</p>
<p>losses</p>
<p id ="lossTotals">0</p>
<p id ="gameOver"></p>
<button onclick ="resetGame()">New Game</button>
<p>Here is the word</p>
<p id = "wordDisplayer">Press New Game to Start</p>
<div id = "wordTiles"></div>
<div class ="fixer"></div>
<button onclick ="checkPlayerGuess()">What Key was Pressed?</button>
<p id ="isThisWorking">What will I say?</p>
<p>Letters Still Available</p>
<p id ="lettersStillAvailable"></p>
<p>Bad Guesses</p>
<p id ="lettersUsed"></p>
<br />
selectedWord ="food";
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = choice;
}
}
}
You can refer this below logic. In this example, I have given some inputs.
var selectedWord ="food";
var displayString = [];
for(var i = 0; i < selectedWord.length; i++){
displayString[i] = "-"
}
var outputEle = document.getElementById("output");
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
function checkPlayerChoiceNew(playerGuess){
var newWord = "";
var regExp = new RegExp(playerGuess,'ig')
selectedWord.replace(regExp, function(value, index){
displayString[index] = value;
return value;
});
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
newWord = displayString.join("");
if(selectedWord == newWord){ alert("You Won the game"); }
//outputEle.innerText = displayString.join(" ");
}
checkPlayerChoiceNew('o');
checkPlayerChoiceNew('g');
checkPlayerChoiceNew('d');
checkPlayerChoiceNew('f');
<div id="output">
</div>

JS: How would I display a decrementing value through an html header? (and more)

Basically, I'm making a simple javascript/html webpage game where you guess a number and you have three chances to guess correctly. I'm having a problem displaying the number of attempts a player has left (It gets stuck at three). The color change that is supposed to occur also doesn't happen.
It also doesn't reset the page's display after a refresh (it takes 5 playthroughs of the game to get it to reset).
Maybe my for loop/if statement is screwy?
Here's my code.
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
The prompt is a blocking event, so you don't see the page update until after the prompts... try the example below, where setTimeout is used to allow a delay...
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
setTimeout(function() {
handleGuess(prompt("Try again!"));
},1000);//wait 1 second
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<br>
Attention. This is a fully workable example, and definitely an "overkill demo" for your "blocking" request.
I've removed the prompt calls with new inputs, and created 2 buttons for the game. One that calls the Start Game, and a second for the "in game try attemps".
I'm assuming you are still learning so this example might be helpful for you,by showing the advantages of separating your code into different elements, based on what they are doing, and also making it easier for you to "upgrade" the features of your game.
I could replace a lot more repeated code to make it look better, but that would not make it so familiar anymore to you.
/*function ChangeDif(Difficulty) {
var i = ""
if (Difficulty == 'easy'){
i = 10;
}
if (Difficulty == 'medium') {
i = 5;
}
if (Difficulty == 'hard') {
i = 3;
}
}
*/
var random = 0;
var start_chances = 3;
var start_attemps = 0;
var x = "";
function startgame() {
document.getElementById("start").hidden = true;
document.getElementById("number").hidden = false;
document.getElementById("again").hidden = false;
document.getElementById("demo").innerHTML = "Pick a number to win the game!";
random = Math.floor((Math.random() * 10) + 1);
//Cheat to see the random number, and make sure the game is working fine
//document.getElementById("cheater").innerHTML= random;
max_chances = start_chances;
step();
}
function lostAchance() {
max_chances--;
if (max_chances > 0) {
step();
} else {
loser();
}
}
function loser() {
//running out of turns
x = "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
endGame();
}
function step() {
var choice = parseInt(document.getElementById("number").value);
if (choice !== random) {
document.body.style.backgroundColor = "#CC0000";
x = "You have " + max_chances + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
document.getElementById("start").hidden = true;
} else {
//win
x = "You win! In " + (start_chances - max_chances) + " attemps <br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
endGame();
}
}
function endGame(){
document.getElementById("start").hidden = false;
document.getElementById("again").hidden = true;
document.getElementById("number").hidden = true;
}
<!DOCTYPE html>
<html>
<body>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'easy')">Easy
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'medium')">Medium
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'hard')">Hard
<br>
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<input type="number" id="number" hidden />
<button type="submit" id="start" onclick="startgame()">Let's PLAY</button>
<button type="submit" id="again" hidden onclick="lostAchance()">Try Again</button>
<p id ="cheater"></p>
</body>
</html>

Adding two form variables with calculating and comparing

I have items "item1 costs $1" and "item2 costs $2"
I made a simple form to calculate the total price of both BUT if the customer will purchase more than 50 items (total items = item1 + item2) I will give him a 50% discount which means the final price will be divided by 2 BUT only if we the total is more than "50".
What I am getting that the price is getting divided by 2 even if the total is only = 10 !!
Here's the jsfiddle:
http://jsfiddle.net/2yTLp/225/
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate(){
var total = x.value + y.value;
if( total >= 50 ){
d.innerHTML = ((x.value * 1.00) + (y.value * 2.00)) / 2;
}
else{
d.innerHTML = (x.value * 1.00) + (y.value * 2.00);
}
}
x.onblur = calculate;
calculate();
#d{
text-indent:20px;
}
<h3>Calculate</h3>
item1 <input id="x" data-in="" type="number" /><br>
<br>
item2 <input id="y" data-in="" type="number" /><br>
<br>
Please Pay and amount of <span id="d"></span>
it's very easy but can't figure it out.
Regards,
You are concatenating strings instead of sum numbers. Please, convert the values to numbers and it works perfectly. See the line commented:
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate(){
//here you need to convert values to numbers
var total = Number(x.value) + Number(y.value);
if( total >= 50 ){
d.innerHTML = ((x.value * 1.00) + (y.value * 2.00)) / 2;
}
else{
d.innerHTML = (x.value * 1.00) + (y.value * 2.00);
}
}
x.onblur = calculate;
calculate();
#d{
text-indent:20px;
}
<h3>Calculate</h3>
item1 <input id="x" data-in="" type="number" /><br>
<br>
item2 <input id="y" data-in="" type="number" /><br>
<br>
Please Pay and amount of <span id="d"></span>
The explanation is if you concatenate this:
var one = "10";
var two = "15";
var result = one + two ; // result string "1015"
But if you change to numbers the sum is perfect
var one = "10";
var two = "15";
var result = Number(one) + Number(two) ; // result int 25
It is very straight and simple
Your code is correct except one thing, you didn't use parseInt,
currently you are concatenating the values instead of adding,
so just replace this code
var total = x.value + y.value;
with this one
var total = parseInt(x.value) + parseInt(y.value);
That's it :)

Categories

Resources