How to make a button in HTML which decrement a variable? - javascript

I am trying to decrement the variable Stock by 1 each time I click the button but it's not working. The value on the website stays the same no matter how many times I click the button:
var Stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = Stock;
}
function ButtonFunction() {
Stock--;
}
<body onload="myFunction">
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>

Your function only changes the value of the Stock variable.
It doesn't change the value of document.getElementById("myText").innerHTML which only gets changed when you call myFunction (something you never do).
You need to:
Actually call myFunction when the document loads
Call it again whenever you change the variable.
let stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = stock;
}
function buttonFunction() {
stock--;
myFunction();
}
document.querySelector("button").addEventListener("click", buttonFunction);
addEventListener("load", myFunction);
<button>ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
Also note that by convention, variable names which start with a capital letter are reserved for classes and constructor functions in JS, so rename your variables.

It looks like the variable is being decremented, but the inner text of the span is not then updated.
Try calling myfunction() after each click ;)

There's a number of things going on here. The one I think you're primarily interested in has been answered by Quentin. Others however remain and are (I think) far better habits to get into than variable naming conventions.
Inline event handlers = bad. Events that can be removed or supplemented = good. Use attachEventListener for the most control.
Functions with names that offer nothing are a pain. Names are the most helpful when they're descriptive.
Functions that change and display a variable can be traps. It's often better to have a third function which calls both a function to change something and another function to display it.
Here's yet another approach:
window.addEventListener('load', onLoaded, false);
function onLoaded(evt) {
displayStock();
document.querySelector('button').addEventListener('click', onButtonPressed, false);
}
var unitsOfStock = 10;
function displayStock() {
document.getElementById('myText').textContent = unitsOfStock;
if (unitsOfStock == 1)
document.getElementById('plural').textContent = '';
else
document.getElementById('plural').textContent = 's';
}
function decreaseStock() {
unitsOfStock--;
}
function onButtonPressed() {
decreaseStock();
displayStock();
}
<button>ClickMe</button>
<h1>The value for Stock is: <span id="myText"></span> unit<span id='plural'></span></h1>

var Stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = Stock;
}
function ButtonFunction() {
Stock--;
myFunction();
}
<body onload="myFunction()">
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>

I hope it helps you. You have to call myFunction to show the new value of Stock variable in myText id in your click handler ButtonFunction().
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var Stock = 10;
function myFunction() {
document.getElementById("myText").innerHTML = Stock;
}
function ButtonFunction() {
Stock--;
myFunction();
}
</script>
</head>
<body onload="myFunction" >
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>
</html>

Whenever you click the 'Click me' button, ButtonFunction() will be called. and document.getElementById("myText") get find the html element with the id myText and reference itself to the html element. innerHTML will allow you to place your html code inside it and innerText allows you to put your text the html element with an id of myText.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var Stock = 10;
function ButtonFunction() {
Stock--;
document.getElementById("myText").innerHTML = Stock;
}
</script>
</head>
<body>
<button onclick="ButtonFunction()">ClickMe</button>
<h1>"The value for Stock is: " <span id="myText"></span></h1>
</body>
</html>

Related

Re-using a variable not possible due to scoping issue. How can I fix this?

I expect to be able to use 'validBet' in a new function. The validBet is the basically the last value of the array 'betButtonsArr'. So the last clicked button will be the bet, not any of the previous. Now I need to be able to use the validBet to determine the bet placed, to calculate loss/winnings in a new function.
The problem is that I get a validBet is undefined error.
I am only using VanillaJS since I want to learn JS first before moving onto libraries.
// starter cash will be 100.
var cashTotal = 100; //Cash currently holding.
var showTotal = document.querySelector("#amount").innerHTML = cashTotal;
var bet = [5, 10, 50, 100]; //Bets you can do.
var numGenerated;
function updateDisplay() {
document.querySelector('#generated_number').innerHTML = "".split.call(numGenerated, "").join("");
}
function highLow(){
var storeNum = Math.floor(Math.random() * 11) + 0;
numGenerated = storeNum;
}
function choiceLow(){
highLow();
updateDisplay();
console.log(numGenerated);
if (numGenerated < 5){
// run function to add winnings
}
else {
// run function to subtract bet amount.
return;
}
}
function choiceHigh(){
highLow();
updateDisplay();
console.log(numGenerated);
if (numGenerated == 5 || numGenerated > 5){
// run function to add winnings.
}
else {
// run function to subtract bet amount.
return;
}
}
var betAmount = [];
function placeBet(){
var betBtn_nodelist = document.querySelectorAll('.bet_amount > button');
var betButtonsArr = Array.prototype.slice.call(betBtn_nodelist);
//
for (var i = 0; i < betButtonsArr.length; i++) {
betButtonsArr[i].onclick = function(){ // when clicked, push value of clicked button to betAmount array for grabbing the placed bet.
betAmount.push(this.value);
console.log(betAmount);
var validBet = betAmount[betAmount.length - 1]; // when multiple bet amounts are clicked, take the last amount chosen, make that the final and valid bet amount.
console.log(validBet) //This is the real bet amount, as explained one line above.
console.log(cashTotal)
}
}
}
placeBet();
function addWinningsAmount(){
}
function subtractBetAmount(){
}
var lower = document.querySelector("#lower");
var higher = document.querySelector("#higher");
lower.addEventListener('click', choiceLow);
higher.addEventListener('click', choiceHigh);
HTML code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Betting Project</title>
<link rel="stylesheet" href="betting.css">
</head>
<body>
<div class="cash_total"><p>Your balance is: <span id="amount"></span>.</p></div>
<h1 style="text-align: center;">BET NOW</h1>
<div class="bet_amount">
<button class="five" value="5">5</button>
<button class="ten" value="10">10</button>
<button class="fifty" value="50">50</button>
<button class="hundred" value="100">100</button>
</div>
<div id="generated_number"></div>
<div class="buttonHolder" style="text-align: center;">
<button id="lower">LOWER</button>
<button id="higher">HIGHER</button>
</div>
<script src="betting.js"></script>
</body>
</html>
I expect to use this and grab the value of the bet. Instead of that, I get the ReferenceError: validBet is not defined. I'm guessing this is a scoping problem, but I have no idea how to best sort this out.
function addWinningsAmount(){
console.log(validBet)
}
when declaring global objects in javascript, you need to declare it at the top. Any variable declared inside a function is limited to that function only.
or else, if the variable still needs to be declared inside the function but with global scope, use window declaration. For eg. window.validBet = betAmount[betAmount.length - 1];. Make sure the function declaring the variable is called before the function accessing the variable.
do not use 'var' while declaring global variables.

Javascript image swap sequence

As a task i am going to make traffic lights change in sequence when a button is pushed.I am going to do this by using a variable and adding one to it each time a image is shown therefore the computer knows what image to display next through the use of if and elses however i am not great at javascript and it will not run i have tried in many different environments for example in dreamweaver and notepad ++ but am getting no where here is what i have got :
<HTML>
<head>
<title>Untitled Document</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap(a)">GO</button>
</body>
<script>
var a = 0
function imageswap(a)
{
if (var a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
var a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.png';
var a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.png';
var a==0;
}
}
</script>
</html>
Thank you for reading and i would appreciate anyones help.
edit:
I have taken on feedback and amended my code but when testing it does not show the image i would like instead the little x .
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0
function imageswap()
{
if (a=0) {
document.getElementById('IMAGE').src='red_empty_empty.gif';
a = a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.gif';
a = a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.gif';
var a=0;
}
}
</script>
</html>
edit:
I have taken into account some recommendations and now when i click the button the first image is shown followed by the second on a second button press however it fails to display the third image and the first and second image dont always work first time.
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0;
function imageswap() {
if (a == 0) {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a += 1;
} else if (a == 1) {
document.getElementById('IMAGE').src = 'empty_amber_empty.gif';
a += 1;
} else {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a = 0;
}
}
</script>
in you first line var a = 0 you declare your counter (the var a part) and initialise it by assigning the value 0 (the a = 0 part), therefore there's no need to declare the variable again later, you just want to update it by assigning new values
so the statement if (var a==0) would be incorrect syntactically, because you can't check if a variable declaration is 0. you can of course check if the previously declared variable has a value of 0, which would be if (a==0)
same goes when you try to increment the counter value. var a + 1; is wrong, because you can't increment by 1 a declaration. you should instead assign to the existing counter, the value of itself plus 1, so a = a + 1;
finally, when you try to reset the counter, var a==0;, (beside the usual declaration error) remember that == is comparison and = is assignment. You shouldn't check if the counter is 0, you should assign the value 0 to the counter to reset it.
hope it helps
I Apply with in console.log(a).It will show the increment of a\
Apply the var a in globel It will increment on each time of you click
And increment Apply with a +=1 instead of a+1
var a = 0
console.log(a)
function imageswap(){
if (a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
a += 1;
console.log(a)
} else if (a==1){
document.getElementById('IMAGE').src='empty_amber_empty.png';
a += 1;
console.log(a)
} else {
document.getElementById('IMAGE').src='empty_empty_red.png';
a =0;
console.log(a)
}
}
<button onclick="imageswap()">GO</button><br>
<img id="IMAGE" width="100" height="200"></img>
Ok Few things you need to take care:
You are passing a within the function imageswap(a) and you are accessing a from the value passed within the function that'll be 0 all the time. Check https://jsfiddle.net/aegwj88g/
You are checking var a==0, var a==1 which is incorrect. It should be like if(a==0) or else if(a==1).
You are trying to assig value to a with var a + 1 which is also incorrect. Left hand side must be a valid variable other than the javascript tokens (check JS naming convention) which stores the value. it should be a=a+1 (or a+=1) just as you do in maths;
Check this fiddle:

onclick does not fire in a link that is created by clicking another link

Javascript function writelink creates a link that fires function hiya. It works when I define and invoke writelink inside script. But, I want the body to contain another link that calls writelink to create a link. This final link fails to fire (but works if I replace hiya with alert). I am a total novice, so I hope it is something obvious. The main idea is that I have to create some links from code, and these have to fire to execute some more code. (If you want me to do this a totally different way, please try to give me a complete example.)
<HTML>
<HEAD>
<script>
function hiya (num){
alert("hiya " + num);
}
function writelink (num){
var htmlstr = "link" + num + "";
document.write(htmlstr);
}
writelink(1);
</script>
</HEAD>
<BODY>
<br>
link2;
<br>
</HTML>
document.write(htmlstr) replaces the entire DOM with the link / htmlstr you are about to insert. Use pure javascript to create the link(s) instead :
function writelink(num){
var link = document.createElement('a');
link.innerHTML='link '+num;
link.href='#';
link.onclick=hiya(num);
document.body.appendChild(link);
}
Just replace writelink() with the code above.
You would typically want to add the link to a certain element instead of just <body>, lets say a <div> with the id menu :
var cnt = document.getElementById('menu');
cnt.appendChild(link);
update
<!doctype html>
<html>
<head>
</head>
<body>
link2
<script>
function hiya(num) {
alert("hiya " + num);
}
function writelink(num){
var link = document.createElement('a');
link.innerHTML='link '+num;
link.href='#';
link.onclick=function(e) {
hiya(num);
}
document.body.appendChild(link);
}
writelink(1);
</script>
</body>
</html>

Passing a variable into a DOM function in Javascript

I took this example from w3schools and modify it to this. The code below is not working.
What I intend to do is hide the div with id "demo1". It is not working. What is the problem?
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(div_id)
{
//here the div_id variable seems to unparsable by the DOM event
document.getElementById(div_id).innerHTML = hello;
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction('demo1')">Click me</button>
<div id="demo1"></div>
<div id="demo2"></div>
</body>
</html>
The variable hello is not defined. You were probably looking to set the innerHTML as a String:
function myFunction(div_id) {
document.getElementById(div_id).innerHTML = "hello";
// -----------------------------------------^-----^
}
DEMO: http://jsfiddle.net/uzuKp/1/
Even though you took an example from W3Schools and modified it, I'd suggest binding events separate from the HTML and storing associated data in data-* attributes. In your example, it can be as something like this:
<p>Click the button to trigger a function.</p>
<button data-div-id="demo1">Click me</button>
<button data-div-id="demo2">Click me</button>
<button data-div-id="demo1">Click me</button>
<div id="demo1">demo1</div>
<div id="demo2">demo2</div>
And the JS:
function clickHandler() {
var targetDivId, targetDiv;
targetDivId = this.getAttribute("data-div-id");
targetDiv = document.getElementById(targetDivId);
targetDiv.innerHTML = "Hello" + new Date().getTime();
}
function loadHandler() {
var buttons, i, j, cur;
buttons = document.getElementsByTagName("button");
for (i = 0, j = buttons.length; i < j; i++) {
cur = buttons[i];
cur.onclick = clickHandler;
}
}
window.onload = loadHandler;
DEMO: http://jsfiddle.net/3K4RD/
Although I would also suggest looking at the following article to see different ways to bind events: addEventListener vs onclick
One final suggestion I have is to not set the innerHTML property. You may have a simple example here, but it's usually a better idea to use DOM methods like appendChild (to add a node) and document.createTextNode (to create text that can be appended). Of course, that would require the contents to be cleared out first, something like:
while (targetDiv.firstChild) {
targetDiv.removeChild(targetDiv.firstChild);
}
targetDiv.appendChild(document.createTextNode("Hello"));
DEMO: http://jsfiddle.net/52Kwe/
You could also store the specific string that needs to be set as the innerHTML as a data-* attribute (especially if it differs between buttons).
UPDATE:
Per your recent edit, the style property is a special property, which is actually a special object with style properties that you need to set. So for your example, you have to set the .style.display value, like:
document.getElementById(div_id).style.display = "none";
document.getElementById(div_id).style.display = 'none';
document.getElementById(div_id).style.visibility= 'hidden';

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Categories

Resources