Changing a value when clicking a button - javascript

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>

Related

Incrementing a displayed number upon a button click

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>

Adding more and more <timepicker> issue. if one gets changed it changes all of them

I have a little problem, I repeat timepicker with *ngFor, but it's not working properly if I changed the time in one of them, it changes in all. And all have a different id. AN IDEA TO MAKE THE WORk PROPERLY?`
COMPONENT.HTML :
<div id="schedule" *ngFor="let i of Arr(num).fill(1)"
style="display: -webkit-inline-flex">
<timepicker id="timer" class="schedulItem" style="margin-top:-28px"
[(ngModel)]="mytime" [showMeridian]="isMeridian"
[minuteStep]="mstep" (ngModelChange)="changed()">
</timepicker>
<button (click)="addSchedule()"> + </button>
</div>
COMPONENT.TS:
Arr = Array; //Array type captured in a variable
num:number = 1;
mytime: Date;
addSchedule() {
this.num = this.num + 1 ;
var length = document.querySelectorAll('.schedul').length
var time = document.getElementById("timer");
time.id += length;
}
changed(): void {
var time = this.mytime.getHours() + ":" + this.mytime.getMinutes();
console.log(time);
}
I found the problem! the model was the problem [(ngModel)]="mytime". All time pickers to the same model and one gets changed it changes all of them.

I'm trying to make a simple program that increses a number each time the user click on a button

hi i'm trying to make a simple progrma that shows how many times a button is clicked on. I'm trying to learn to use namespaces. My problem is that then i click on the button the number that is displayed is just undefined.
var $S = {};
$S.antalClick = 0;
$S.click = function() {
$S.antalClick = +1;
document.getElementById("visa").innerHTML = $S.antalCLick;
}
<input type="button" value="click me" onClick=$S.click() /> <br/>
<div id="visa"></div>
There is an error in your $S.click function, replace
$S.antalClick = +1; by $S.antalClick += 1;
this is a shortcut to mean $S.antalClick = $S.antalClick + 1
You could shorten the previous answer further with $S.antalClick++;. The ++ signifies increasing a value by 1.
Use $S.antalClick++;:
var $S = {};
$S.antalClick = 0;
$S.click = function() {
document.getElementById( 'visa' ).innerHTML = $S.antalClick++;
}
<input type="button" value="click me" onClick=$S.click() />
<div id="visa"></div>

Getting the value from an HTML button using JavaScript

I am making a calculator, I have already created the calculator in html and css but I am trying to move forward by making the button clicks register in the display which is what my problem is right now. I am fairly new to JavaScript so if someone could point me in the right direction on how to do it or where to find the answer I would appreciate it.
This is a the portion I am working on, trying to get button '7' to register so I can do the others.
<div class="container-fluid calc" >
<div class="display">
<label type="text" id="screen">0</label>
<div class="buttons">
<button onClick='calculate()' id='myButton'>7</button>
<button>8</button>
<button>9</button>
Here is the JS I put together
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
calculate();
You need to update from
var num = document.getElementById('#myButton').contentValue;
to
var num = document.getElementById('myButton').innerHTML;
You should use the .innerHTML function instead of the .contentValue function to do this, also, you shouldn't use a # in document.getElementById this is used in jQuery, so just the ID is enough
function calculate(){
var num = document.getElementById('myButton').innerHTML;
document.getElementById('screen').innerHTML = num;
}
calculate();
Hope this helps!
Update
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
to
function calculate(){
var num = document.getElementById('myButton').innerText;
document.getElementById('screen').innerText = num;
}
Another option is you can is data attribute like this :
<button onClick='calculate()' id='myButton' data-value="7">7</button>
and get it like this :
$("#myButton").attr("data-value");

Need Help in adding div elements which have integer values

I have three DIV whose content are integer values and are updated frequently from another source. My main idea here was to take the content of the three divs parse it into float or integer , add them and display the total in another div. I am looking forward to handle the content in div using a onchange() function, because the the content in them will be changing frequently. Below is my code, its currently not working, i will really appreciate it if you give me a hand of help with this.
The content in this divs will be frequently updated using a text input, you can create a text inout that manipulates the first div then displays the whole sum
Thanks in advance.
<script>
function total() {
var value1 = parseFloat($('#div1').innerHTML ()) || 0;
var value2 = parseFloat($('#div2').innerHTML ()) || 0;
var value3 = parseFloat($('#div1').innerHTML ()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body >
<div id="mywraper">
<div id="div1" onchange="total()">
4
</div>
<div id="div2" onchange="total()">
5
</div>
<div id="div2" onchange="total()">
6
</div>
</div>
<div id="total_div">
Total $<span id="total"></span>
</div>
</body>
</html>
Use this html()
<script>
function total() {
var value1 = parseFloat($('#div1').html()) || 0;
var value2 = parseFloat($('#div2').html()) || 0;
var value3 = parseFloat($('#div1').html()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
Try this:
function total() {
// fetch text using 'text' method and then convert string into number using '+' operator
var value1 = +$('#div1').text() || 0;
var value2 = +$('#div1').text() || 0;
var value3 = +$('#div1').text() || 0;
var total = value1 + value2 + value3;
$('#total').html(total);
}
http://jsfiddle.net/uxajjk1b/2/
Use text() instead of innerHTML, like so:
<script>
function total() {
var value1 = parseFloat($('#div1').text()) || 0;
var value2 = parseFloat($('#div2').text()) || 0;
var value3 = parseFloat($('#div1').text()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
I didn't really want to answer, as this might be difficult to solve due to the fact that we have no idea how the values are updated in the first place. However, I ended up doing relatively extensive example, so here we are.
So as mentioned before, onChange requires user input or action to detect any change. So that means your total() would only trigger once when the page is loaded ( assuming it's placed right before </body> ).
The best method would be to also stick the total() inside the original function that changes the values inside the html elements. This way total() is also triggered each time.
I couldn't resist making the total() more dynamic. This way, if you add or remove those child divs, the javascript won't need to be updated.
Here's a link to the original jsfiddle
var parentContainer = $('#mywraper');
function total() {
var values = {}; // Optional****
var total = 0;
// Loops through parent containers children ( in this case div elements ).
parentContainer.children().text(function( i, val ) {
var value = parseInt( val );
// Creates a variable where the variable name is based on the current elements index and value is based on the text inside the element.
values[ 'child_' + (i+1) ] = value; // Optional****
// Sums up all the values
total += value;
});
// The optional lines enable you independently check each value, for example:
// console.log( values.child_1 )
// Push total into the #total element.
$('#total').html( total );
}
total();
Here's an example where the values are updated with a click event. So what you do is just add the total() inside the click event as well.
function total() {
var parentContainer = $('#mywraper'),
total = 0;
parentContainer.children().text(function( i, val ) {
total += parseInt( val );
});
$('#total').html( total );
}
total();
$('#updateBtn').on("click", function() {
$('#mywraper').children().text(function( i, val ) {
return parseInt( val ) + 1;
});
total();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mywraper">
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div id="total_div">
Total $<span id="total"></span>
</div>
<button id="updateBtn">Update values</button>

Categories

Resources