Incrementing a displayed number upon a button click - javascript

I would like to increment the number displayed by the h3 tag whenever the button is pressed but can't seem to find the solution to do this.
var outPut = document.querySelector("#outPut");
var button1 = document.querySelector("#button1");
button1.addEventListener("click", () => {
var num = 0;
num += 1;
outPut.innerHTML = num;
})
<h1>Counter</h1>
<div id="display">
<h3 id="outPut">0</h3>
</div>
<button id="button1">Count Up</button>
<button id="button2">Count Down</button>
<button id="button3">Count Up X2</button>
<button id="button4">Count Down X2</button>

You have declared the variable (num) in the wrong scope. Since you have declared the counter variable (num) inside the function, in each click the variable is created with the initial value 0. To retain the previous value declare the variable outside the function.
Also, I will suggest you to use innerText or textContent instead of innerHTML if the text is a plain text (not htmlString).
var outPut = document.querySelector("#outPut");
var button1 = document.querySelector("#button1");
var num = 0;
button1.addEventListener("click", () => {
num += 1;
outPut.textContent = num;
})
<h1>Counter</h1>
<div id="display">
<h3 id="outPut">0</h3>
</div>
<button id="button1">Count Up</button>
<button id="button2">Count Down</button>
<button id="button3">Count Up X2</button>
<button id="button4">Count Down X2</button>

Related

Changing a value when clicking a button

I am in the process of learning Javascript and at the moment I'm only using vanilla js to code stuff.
I'm trying to make 2 button (+ and -) to add and subtract a number.
Here's what I have so far:
let value = document.querySelector("#number");
let add = document.querySelector("#add").addEventListener("click", function(value){
add = value++;
document.querySelector("#number").textContent = add;
});
With the above code, when I click my button my p tag changes to NaN. It is 0 form the start.
Goal it to make it 1.
In case you need the HTML code then this is what I have:
<div class="content">
<button id="add">+</button>
<p id="number">0</p>
<button id="sub">-</button>
</div>
You need to set a global var and add and subtract value on that.
You also need to check value is more then zero using ternary operator (if condition) so that the value is always displayed above zero when subtracting
Live Demo
let value = document.querySelector("#number");
//Store value
let valueNumber = 0
//Add value
document.querySelector("#add").addEventListener("click", function(value) {
valueNumber++;
document.querySelector("#number").textContent = valueNumber;
});
//Subtract value
document.querySelector("#sub").addEventListener("click", function(value) {
valueNumber--;
document.querySelector("#number").textContent = valueNumber > 0 ? valueNumber : 0;
});
<div class="content">
<button id="add">+</button>
<p id="number">0</p>
<button id="sub">-</button>
</div>
Even though the answer has been given, I'd like to share mine.
document.querySelector("#add").onclick = function(){
let num = number.innerText;
number.innerText = num/1 + 1;
}
document.querySelector("#sub").onclick = function(){
let num = number.innerText;
if(num > 0){
number.innerText = num/1 - 1;
}
}
<div class="content">
<button id="add">+</button>
<p id="number">0</p>
<button id="sub">-</button>
</div>

Multiple single onClick events

I'm just messing around on JavaScript. I want to create two single on-click buttons, each which serve separate functions. However, the first button's response is always that of the second if that group of code is in. It works fine independently.
I've double checked online and tried a few functions, but everything comes back to multiple-function buttons.
I'm not super advanced and I just do random programming for fun.
If the yes button is clicked, then "Good" should appear. If the no button is clicked, then "Bad" should appear.
When both groups of code are together, "Bad" is always shown, regardless of the button shown. If only the first group of code is isolated, then the result is "Good".
function myFunction() {
var str = "Good";
var result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
document.getElementById("happy").innerHTML = result;
}
</script>
<button onclick="myFunction()">No</button>
<p id="sad"></p>
<script>
function myFunction() {
var str = "Bad";
var result = str.link("https://www.tacobell.com/");
document.getElementById("sad").innerHTML = result;
}
Do you like tacos?
<br />
<button onclick="myFunction()">Yes</button>
<p id="happy"></p>
You can also use a single click event function for both of your buttons.
See below code -
function myFunction(elem) {
var btnHtml = elem.innerHTML;
var str = "Good";
var id = "happy"
if(btnHtml == "No"){
str = "Bad";
id = "sad";
}
var result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
document.getElementById(id).innerHTML = result;
}
Do you like tacos?
<br />
<button onclick="myFunction(this)">Yes</button>
<p id="happy"></p>
<button onclick="myFunction(this)">No</button>
<p id="sad"></p>
You can do something like this, one function for both onclick events.
HTML
<p>Click the button to trigger a function.</p>
<button onclick="myFunction('yes')">Yes</button>
<button onclick="myFunction('no')">No</button>
<p id="demo"></p>
Javascript
function myFunction(value)
{
document.getElementById("demo").innerHTML=value;
}
Here's the fiddle
http://jsfiddle.net/840Larsn/
It is because you are using Function constructor and the functions are created in the global scope and therefore the second function overwrites the first one.
You can refer to here to see the definition.
You can use jquery if you wish,its simple
$('.clickbtn').click(function(e){
var str,result ;
var data = $(this)
if(data.attr('data-id')==1)
{
str = "Good";
result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
$("#text").html(result)
}
else
{
str = "Bad";
result = str.link("https://www.tacobell.com/");
$("#text").html(result)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Do you like tacos?
<br />
<button class="clickbtn" data-id=1>Yes</button>
<button class="clickbtn" data-id=2>No</button>
<p id="text"></p>
You should name your function differently:
In fact when you declare the second function in your original code it overwrites the first one because they have the same name.
function myGoodFunction() {
var str = "Good";
var result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
document.getElementById("happy").innerHTML = result;
}
function myBadFunction() {
var str = "Bad";
var result = str.link("https://www.tacobell.com/");
document.getElementById("sad").innerHTML = result;
}
Do you like tacos?
<br />
<button onclick="myGoodFunction()">Yes</button>
<p id="happy"></p>
<button onclick="myBadFunction()">No</button>
<p id="sad"></p>

Toggle button back to default html

I'm trying to change the innerHTML of my button back to default. It works with changing the innerHTML the first time, but then I can't get it back to default.
I've tried using booleans to toggle back and forth, but my code just won't execute the second part of the function.
function money() {
var money = document.getElementById('money');
var text = "normal";
if (text == "normal") {
money.innerHTML = "<h1>Let me ask you</h1><p>Does this work<p>";
text = "changed";
} else {
money.innerHTML = "<h1>Money Laundering</h1><p>Click For More Info</p>";
text = "normal";
}
}
<div id="practiceContainer">
<h1 id="practiceHeader">Practice Areas</h1>
<div class="lawgrid">
<button class="practicesBox" id="money" onclick="money()">
<h1>Money Laundering</h1>
<p>Click For More Info</p>
</button>
</div>
</div>
I expected my code to change back to default html, but it doesn't happen.
You set the text variable to "normal" at the beginning of the function, therefore when your code reaches your if logic, text will always be "normal".
Consider simply moving the text variable outside of your function, so that it doesn't keep resetting with each click.
var text = "normal";
var btnMoney = document.getElementById('money');
function money() {
if (text == "normal") {
btnMoney.innerHTML = "<h1>Let me ask you</h1><p>Does this work<p>";
text = "changed";
} else {
btnMoney.innerHTML = "<h1>Money Laundering</h1><p>Click For More Info</p>";
text = "normal";
}
}
<div id="practiceContainer">
<h1 id="practiceHeader">Practice Areas</h1>
<div class="lawgrid">
<button class="practicesBox" id="money" onclick="money()">
<h1>Money Laundering</h1>
<p>Click For More Info</p>
</button>
</div>
</div>

How do I clear the innerHTML of a h1 tag

I'm just trying to make a simple mobile-based calculator. So far I've managed to display the digits pressed up to a certain character limit. I'm trying to make it so it clears the digits within the h1 tag that serves as the display.
I've tried using .innerHTML = "", but that isn't working. How should I fix this?
HTML
<body>
<h1 id="display">Calculator</h1>
<div class="buttons container" id="arithmetic">
<button onclick="clear()" onkeypress="clear()">AC</button>
<button><sup>+</sup>⁄<sub>−</sub></button>
<button>%</button>
<button>÷</button>
<button onclick="number(7)" onkeypress="number(7)">7</button>
<button onclick="number(8)" onkeypress="number(8)">8</button>
<button onclick="number(9)" onkeypress="number(9)">9</button>
<button>×</button>
<button onclick="number(4)" onkeypress="number(4)">4</button>
<button onclick="number(5)" onkeypress="number(5)">5</button>
<button onclick="number(6)" onkeypress="number(6)">6</button>
<button>−</button>
<button onclick="number(1)" onkeypress="number(1)">1</button>
<button onclick="number(2)" onkeypress="number(2)">2</button>
<button onclick="number(3)" onkeypress="number(3)">3</button>
<button>+</button>
<button>.</button>
<button id="doubleSpace" onclick="number(0)" onkeypress="number(0)">0</button>
<button>=</button>
</div>
<div class="calcOptions container">
<button>Arithmetic</button>
<button>Algebra</button>
<button>Calculus</button>
<button>Statistics</button>
</div>
</body>
JavaScript
var currentQuery;
var pastQuery;
var queryLength = document.getElementById("display").innerHTML.length;
function number(n) {
if (document.getElementById("display").innerHTML == "Calculator") {
document.getElementById("display").innerHTML = "";
}
if (queryLength >= 15) {
} else {
currentQuery = document.getElementById("display").innerHTML;
currentQuery += n;
document.getElementById("display").innerHTML = currentQuery;
}
}
function clear() {
currentQuery = "";
document.getElementById("display").innerHTML = currentQuery;
}
You can't name a javascript function with clear(), and the value of queryLength should set after the document ready replace your code by:
var currentQuery;
var pastQuery;
var queryLength;
document.addEventListener("DOMContentLoaded", function(event) {
var queryLength = document.getElementById("display").innerHTML.length;
})
function number(n) {
if (document.getElementById("display").innerHTML == "Calculator") {
document.getElementById("display").innerHTML = "";
}
if (queryLength >= 15) {
} else {
currentQuery = document.getElementById("display").innerHTML;
currentQuery += n;
document.getElementById("display").innerHTML = currentQuery;
}
}
function clearValue() {
currentQuery = "";
document.getElementById("display").innerHTML = currentQuery;
}
and the clear button with:
<button onclick="clearValue()" onkeypress="clearValue()">AC</button>
The problem is that the name of your function clear is already used by this native function document.clear(). Here is a deeper look on why this native function is called and not your function: Is “clear” a reserved word in Javascript?.
The solution is to simply rename your clear() function to something else e.g. allcancel()
You can try using .innerText = "".

Javascript to find content

Hi I am using code below, but getting 'undefined' as a result. How to fix this?
I am not sure how to call for a class within a class.
function myFunction() {
document.getElementById("mydiv").innerHTML = document.getElementsByClassName("inline-keyword-marker").innerHTML;
}
<span class="inline-keyword-marker valid">Product</span>
<p>Click the button to change the text in "mydiv".</p>
<button onclick="myFunction()">Try it</button>
<p id="mydiv">***</p>
Note: As getElementS states, getElementsByClassName returns an array like HTMLCollection.
So inorder to access the first element (your class inline-keyword-marker), you need to add [0] to your method like this:
document.getElementsByClassName('inline-keyword-marker')[0]
function myFunction() {
document.getElementById("mydiv").innerHTML = document.getElementsByClassName("inline-keyword-marker")[0].innerHTML;
}
<span class="inline-keyword-marker valid">Product</span>
<p>Click the button to change the text in "mydiv".</p>
<button onclick="myFunction()">Try it</button>
<p id="mydiv">***</p>
You might also to read this. It explains your issue more detailed than I did.
To handle all your classes, you can use this method:
function myFunction() {
var classes = document.getElementsByClassName('inline-keyword-marker'); // Get all elements
var myDiv = document.getElementById('mydiv'); // Get the div for the result
myDiv.innerHTML = ""; // At first, we clear the result div; not neccessary, just for the optic
// Because we got a HTMLCollection back, we need to loop through it
for (var i = 0; i < classes.length; i++) {
myDiv.innerHTML += classes[i].innerHTML + "<br>"; // With [i] we access every element -> at first the first one, then the second on and so on
// I also added a <br> tag, so the results get append beneath each other, not next to each other
}
}
<span class="inline-keyword-marker valid">Product1</span>
<span class="inline-keyword-marker valid">Product2</span>
<span class="inline-keyword-marker valid">Product3</span>
<span class="inline-keyword-marker valid">Product4</span>
<span class="inline-keyword-marker valid">Product5</span>
<p>Click the button to change the text in "mydiv".</p>
<button onclick="myFunction()">Try it</button>
<p id="mydiv">***</p>
Problem :
document.getElementsByClassName returns an array and not a single value so in order to select one you can do this [i] where is the index of the elements so :
document.getElementsByClassName("inline-keyword-marker")
becomes :
document.getElementsByClassName("inline-keyword-marker")[0]
and selects the first element with class inline-keyword-marker
So total JavaScript becomes :
myFunction = () => {
document.getElementById("mydiv").innerHTML = document.getElementsByClassName("inline-keyword-marker")[0].innerHTML;
}
Shorter :
myFunction = () => (d=document).getElementById("mydiv").innerHTML = d.getElementsByClassName("inline-keyword-marker")[0].innerHTML
<span class="inline-keyword-marker valid">Product</span>
<p>Click the button to change the text in "mydiv".</p>
<button onclick="myFunction()">Try it</button>
<p id="mydiv">***</p>

Categories

Resources