innerHTML not updating
Your error was using, InnerHTML on TOTAL witch was set like this
var Total = document.getElementById("Total").textContent;
Instead of using innerHTML in just
var Total = document.getElementById("Total");
See here: When you click #taco1
you add the values to the total.
Try it here:
(function() {
var T1 = document.querySelector('#taco1'); T1.addEventListener("click", function(e) { if (e.target.tagName === "IMG") { var Total = document.getElementById("Total").textContent; var price = document.getElementById("p1").textContent; var nbrprice = parseInt(price); var nbrTotal = parseInt(Total); console.log("value of nbrprice is " + nbrprice) console.log("nbrprice is a " + typeof(nbrprice)); console.log("nbrTotal is a " + typeof(nbrTotal)); var sum = Number(price) + Number(Total); console.log("sum is a " + typeof(sum)); console.log("value of sum is " + sum);; var sumtxt = (sum + nbrprice); console.log("sumtxt is a " + typeof(sumtxt)); console.log("value of sumtxt is " + sumtxt);; console.log("sumtxt is a " + typeof((sumtxt).toString())); console.log("value of sumtxt is " + (sumtxt).toString());; document.getElementById("Total").innerHTML = sumtxt; console.log(sumtxt); } }, false);
})();
<div id='taco1'> <img src="https://placehold.it/300x100" width="300" /> <p>Taco One Price: <span id="p1">4</span> </p></div><div id='taco2'> <img src="https://placehold.it/300x100" width="300" /> <p>Taco Two Price: <span id="p2">5</span> </p></div>
<div>Total: $<span id="Total">0</span></div>
JavaScript innerHTML not updating element
The element doesn't exist at the time you're attempting to set a value. You need to call this after the <h1>
has been added to the DOM.
You can either move this <script>
tag down further, or add your logic to a function which ought to be called when the document has been loaded:
window.onload = function() {
/* Add your logic here */
}
Demo: http://jsfiddle.net/Lr2Hm/
InnerHTML not updating in JavaScript
The variable currentGuess
in the processGuess()
function is local to that function, because function parameters are always local variables. So when it updates this variable, it doesn't affect the global variable that setElementValues()
puts into .innerHTML
.
You need to be consistent in whether you're passing information through parameters or using global variables. If you're passing the current guess as a parameter, it should return the updated value, and the caller can assign the global variable, e.g.
onclick="currentGuess = processGuess('high', currentGuess);"
Or you could just stick to using the global variable, so you don't need to pass it as a parameter. It would then be just:
onclick="processGuess('high')"
Here's your code using the latter method.
var guess = 0; // Number of guesses remainingvar currentGuess = 0;
function runGame() {
//get variables from the input fields in HTML form and convert to integer var low = parseInt(document.getElementById('lowNum').value); var high = parseInt(document.getElementById('highNum').value); //boolean that checks if the game is won if ( document.getElementById('compGuess').value !== '' ) { guess = parseInt(document.getElementById('compGuess').value); } else { alert ("You have to let the computer have at least one guess!" ); } //input validation if(low < high && low > 0 && high <= 50 && guess > 0 && guess <= 10) { // Input validated //alert("Low number: " + low + "\nHigh Number: " + high + "\nComputer Guesses: " + guess); currentGuess = getRndInteger(low, high); setElementValues(); showButtons(); } else { alert("Invalid selection. Make sure that the number range is between 1 and 50 and guesses are higher than zero."); } }
function processGuess( status ) { if ( status == 'high' ) { currentGuess = currentGuess - 1; } else if ( status == 'low' ) { currentGuess = currentGuess + 1; } else if ( status == 'correct' ) { wonGame(); }//troubleshooting codeconsole.log( status ) ;console.log( currentGuess );setElementValues(); return;}
function setElementValues() { console.log( 'setting values' ); document.getElementById("computerGuessVal").innerHTML = currentGuess; document.getElementById("guessesLeft").innerHTML = guess;
}
//generate computer guessfunction getRndInteger(low, high) { high = Math.floor(high); low = Math.ceil(low); return Math.floor(Math.random() * (high - low + 1) ) + low;} //make bottom buttons visibilefunction showButtons() { document.getElementById("higher").style.visibility = 'visible'; document.getElementById("lower").style.visibility = 'visible'; document.getElementById("correct").style.visibility = 'visible';}//hide bottom buttonsfunction hideButtons () { document.getElementById("higher").style.visibility = 'none'; document.getElementById("lower").style.visibility = 'none'; document.getElementById("correct").style.visibility = 'none';
}
function wonGame () {
/* document.getElementById("lowNum").innerHTML = 1; document.getElementById("highNum").innerHTML = 1; document.getElementById("guess").innerHTML = 1; document.getElementById("computerGuessVal").innerHTML =" "; document.getElementById("guessesLeft").innerHTML = " "; alert("Looks like the computer guessed correctly. Thanks for playing!"); */ alert("Function yo");}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="generator" content="PSPad editor, www.pspad.com"> <title>ITEC345-101 Assignment 1</title> <script language="JavaScript" src="ITEC345_101_FERGUSON_LAB1.js"></script> </head> <body> <h1>Welcome to the number guessing game. Select a range of numbers between 1 and 50 and the computer will try to guess it.<br> Tell the computer how many guesses it gets and see if you can stump it!</h1><br> <h2>Pick a number range between 1 and 50</h2> Low Number: <input type="number" value = "1" name="lowNum" id="lowNum" ><br> High Number: <input type="number" value= "1" name="highNum" id="highNum"><br> <br> <br> <h2>Now think of a number inside that range</h2> Number of guesses computer gets (Max 10):<input type="number" value = "1" name="compGuess" id="compGuess"> <br> <br> <input type="button" value="Start" onclick="runGame()"> <br> <br> <br> <font size="12">Current Computer Guess:</font> <h1 id="computerGuessVal"> </h1> <font size="10">Guesses left:</font><h1 id="guessesLeft"></h1> <br> <br> <input type="button" value="Higher" id="higher" style= "visibility:hidden" onclick="processGuess('high')"> <input type="button" value="Lower" id="lower" style= "visibility:hidden" onclick="processGuess('low')"> <input type="button" value="Correct" id="correct" style= "visibility:hidden" onclick="processGuess('correct')"> </body></html>
innerHTML Not Updating Text
getElementsByClassName()
returns collection. You have to use proper index with that.
Change:
document.getElementsByClassName('currMonth').innerHTML = MONTHS[month];
document.getElementsByClassName('currYear').innerHTML = year;
To:
document.getElementsByClassName('currMonth')[0].innerHTML = MONTHS[month];
document.getElementsByClassName('currYear')[0].innerHTML = year;
Setting innerHTML: Why won't it update the DOM?
innerHTML
evaluates to a string. I'm not sure why you would expect anything different. Consider this:
var a = 'foo'; // now a = 'foo'
var b = a; // now a = 'foo', b = 'foo'
b = 'bar'; // now a = 'foo', b = 'bar'
Re-assigning b
doesn't change a
.
Edited to add: In case it's not clear from the above, if you want to change innerHTML
, you can just assign to it directly:
document.getElementById("my_div").innerHTML = "Hello";
You don't need, and can't use, an intermediary variable.
Related Topics
How to Get 30 Days Prior to Current Date
Get Image from Json File Using JavaScript and Display in HTML Img Tag
How to Close an Open Collapsed Navbar When Clicking Outside of the Navbar Element in Bootstrap 3
Get Docx File Contents Using Javascript/Jquery
Get Previous Value on Input Event
Javascript Generate Random Numbers Without Repeating
Create React App Breaks After Deployment on Refresh 404 With Nginx
How to Change Iframe Src Without Reloading the Iframe
Reduce the Build Time in a Large Angular 8
React-Redux State Lost After Refresh
Check If a Number Has Repeated Digits
Getting the Reason Why Websockets Closed With Close Code 1006
Get Request Works With Postman But Why Doesn't It Work With Reactjs Fetch
Bootstrap 4 Display Dropdown Submenu on the Right Side
How to Trigger Click Event on Select Element (Not Change)