Calculate numbers on click [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Im new to jQuery
If I have list like this:
add one
add two
add three
How can I calculate these in container #calculate.
When
add one
is clicked it should add 1 to container, when
add two
is clicked it should show 3 in container and so should be possible to click these endlessly and every time it should multiply number you click to add

var TotalAmount = 0;
function btnClick(Param) {
TotalAmount += Number(Param);
console.log(TotalAmount);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnOne" onclick="btnClick(1)">Add one</button>
<button id="btnTwo" onclick="btnClick(2)">Add two</button>
<button id="btnThree" onclick="btnClick(3)">Add three</button>

Use a global variable, which is initialized to 0.
use onClick to call the function you want, in that case add(num) and set the counter value to the result div.
var counter = 0;
function add(num){
counter += num;
$("#res").html(counter);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="res">0</div>
<button onClick="add(1)">Add One</button>
<button onClick="add(2)">Add Two</button>
<button onClick="add(3)">Add Three</button>

Try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">0</div>
<button value="1" onClick="sum(this.value)">Add One</button>
<button value="2" onClick="sum(this.value)">Add Two</button>
<button value="3" onClick="sum(this.value)">Add Three</button>
<script>
var total = 0;
function sum(num){
total += parseInt(num);
$("#result").html(total);
}
</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
Result: <span id="result"></span><br />
Number of clicks: <span id="clickNumber"></span><br />
</div>
<div>
<button onclick="addFunction(1)">
Add One
</button>
<button onclick="addFunction(2)">
Add Two
</button>
</div>
<script>
let result = 0;
let clickNumber = 0
function addFunction(n){
result += n;
clickNumber++;
$("#result").text(result);
$("#clickNumber").text(clickNumber);
}
</script>

var total = 0;
function add(num){
if(total==0){
total += num;
$("#res").html(total);
}else{
total *= num;
$("#res").html(total);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="res">0</div>
<button onClick="add(1)">Add One</button>
<button onClick="add(2)">Add Two</button>
<button onClick="add(3)">Add Three</button>

You can bind a click event get the text of button to do this as below
$("button").click(function(){
nummber = nummber +( +this.text());
});
this you dont need to attach click listner in html add a class to button to find only the calculator button in javascript

Related

on click increment a button text using javascript? [duplicate]

This question already has answers here:
Increment a number inside a div?
(4 answers)
Closed 3 years ago.
I am creating buttons on click I would like to increment button text on every time a user creates a new button
HTML
<button id="btn">Add button</button>
<div id="movie-block">
</div>
$("#btn").on("click", function(){
var newMovieBlockButton = $("<div class='movie-button w'>Button1<div>");
$("#movieblock" + movieid).append(newMovieBlockButton);
})
I want when user click add button new button should be created starting with eg
button1, if he creates another button it should be button2 etc etc
How can I accomplish that using jquery?
In each click, you can take the length of the button with class movie-button and concatenate that with the text:
$("#btn").on("click", function(){
var len = $('.movie-button').length + 1;
var newMovieBlockButton = $("<div class='movie-button w'>Button"+ len +"<div>");
$("#movie-block").append(newMovieBlockButton);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="btn">Add button</button>
<div id="movie-block">
</div>
A quick google search would have helped.
<button id="btn">Add button</button>
<div id="movie-block">
</div>
let counter = 1;
$("#btn").on("click", function(){
var newMovieBlockButton = $(`<div class='movie-button w'>Button${counter}<div>`);
$("#movieblock" + movieid).append(newMovieBlockButton);
counter++;
})
<!DOCTYPE html>
<html>
<body>
<button onclick="append()">Try it</button>
<div id="myDIV">
New Paragraphs will add on this div
</div>
<script>
function append() {
var para = document.createElement("P");
para.innerHTML = "This is a paragraph.";
document.getElementById("myDIV").appendChild(para);
}
</script>
</body>
</html>
Hope this will help

More efficient way to bind variables with buttons? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have 3 different buttons that when clicked on will increment specific variable by 1.
Instead of writing 3 different on clicks, is there more efficient way to do this?
I know i can use data attributes to bind button with correct element, but i don't know how to do that with variables.
var x1 = 0;
var x2 = 0;
var x3 = 0;
$('.btn1').on('click', function() {
x1 += 1;
$('#panel1').html(x1);
});
$('.btn2').on('click', function() {
x2 += 1;
$('#panel2').html(x2);
});
$('.btn3').on('click', function() {
x3 += 1;
$('#panel3').html(x3);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn1">#btn1</button>
<button class="btn2">#btn2</button>
<button class="btn3">#btn3</button>
An approach using id's or whatever attribute and arrays:
var x = [];
x[1] = 0;
x[2] = 0;
x[3] = 0;
$('.btn').on('click', function() {
var pos = $(this).attr("id");
x[+pos] += 1;
$('#panel'+pos).html(x[pos]);
});
in HTML:
<button class="btn" id="1">#btn1</button>
<button class="btn" id="2">#btn2</button>
<button class="btn" id="3">#btn3</button>
Give them the same class and make it one click listener and put a data attr on each button with the variable name and the panel name. something like this, put all the variables in one object so you can access them also if they are global variables you can access them like this window[variableName]
As always, use a function to abstract over duplicated code.
function counter(buttonSelector, outputSelector) {
var x = 0;
$(buttonSelector).on('click', function() {
x += 1;
$(outputSelector).text(x); // btw, don't use `html`
});
}
counter('.btn1', '#panel1');
counter('.btn2', '#panel2');
counter('.btn3', '#panel3');
You can further remove repetition by putting those calls (or just the function body) in a loop, and/or adjust your selectors appropriately, but for three calls it's not yet worth it.
you can use an array instead of multi variables.
now give all buttons a specific class like btn.
then :
var ar=[0,0,0];
$('.btn').on('click',function(){
var x=$(this).html(); //if text of buttons is #btn1,#btn2 , ....
var num=parseInt(x.substr(x.length - 1));
ar[num]++;
});
Store the count in data attributes instead of a variable.
$('button[data-out]').on('click', function() { // bind on every button
// $(document).on('click, 'button[data-out]', function() { // or use event delegation with one click event
var btn = $(this) // reference the element
var cnt = (btn.data('count') || 0) + 1 // read count or default to zero and increment
btn.data('count', cnt) // update the count data attribute
$(btn.data('out')).text(cnt) // update your text output
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn1" data-out="#panel1">#btn1</button>
<button class="btn2" data-out="#panel2">#btn2</button>
<button class="btn3" data-out="#panel3">#btn3</button>
I would either give your buttons a common class, or you could just bind your click event to the button element if you don't have others you need to worry about. Then use the index of the button being clicked to match it to the div you want to change. Essentially a one-liner:
$('button').on('click', function() {
$('div').eq($(this).index('button')).html(+$('div').eq($(this).index('button')).text() + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn1">#btn1</button>
<button class="btn2">#btn2</button>
<button class="btn3">#btn3</button>
Parts explained:
$(this).index('button') gets the index of the button among the button elements. See .index().
$('div').eq($(this).index('button')).text() select the div using the index above. See .eq()
+ converts the string content of the div to a number. Also could have used parseInt()
Store the variables as properties of an object.
Use a data-* attribute on each button to store what variable it is
supposed to match.
Bind all buttons to one handler.
In the handler, check the clicked button's data- attribute and
update the associated Object property as needed.
let variableObject = {
x1:0,
x2:0,
x3:0
}
$('.btn').on('click', function() {
variableObject[this.dataset.key]++;
$('#panel' + this.dataset.key.charAt(1)).text(variableObject[this.dataset.key]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">0</div>
<div id="panel2">0</div>
<div id="panel3">0</div>
<button class="btn" data-key="x1">#btn1</button>
<button class="btn" data-key="x2">#btn2</button>
<button class="btn" data-key="x3">#btn3</button>
Having said that, do you really need the variables in the first place? Why can't you just adjust the HTML content directly and anytime you may need that data, simply extract it.
$('.btn').on('click', function() {
// Get current value of associated panel
let current = $("#" + $(this).data("key")).text();
// Set text of associated panel to old value plus one
$("#" + $(this).data("key")).text(++current);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">0</div>
<div id="panel2">0</div>
<div id="panel3">0</div>
<button class="btn" data-key="panel1">#btn1</button>
<button class="btn" data-key="panel2">#btn2</button>
<button class="btn" data-key="panel3">#btn3</button>
Here is a version that generates the initial variables too, so it should be scalable.
bindVars = {}
$('[data-bind-id]').each(function() {
var xi = "x" + $(this).data('bind-id');
var pi = "#panel" + $(this).data('bind-id');
bindVars[xi] = 0;
$(this).on('click', function() {
bindVars[xi] += 1;
$(pi).text(bindVars[xi]);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">0</div>
<div id="panel2">0</div>
<div id="panel3">0</div>
<button data-bind-id='1'>#btn1</button>
<button data-bind-id='2'>#btn2</button>
<button data-bind-id='3'>#btn3</button>
Something like this
vars = {
'x1':0,
'x2':0,
'x3':0
}
$('.btn').on('click', function(){
var vn = $(this).data('varname');
var ps = $(this).data('panel-selector');
vars[vn] += 1;
$(ps).text(vars[vn]);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn" data-varname='x1' data-panel-selector='#panel1'>#btn1</button>
<button class="btn" data-varname='x2' data-panel-selector='#panel2'>#btn2</button>
<button class="btn" data-varname='x3' data-panel-selector='#panel3'>#btn3</button>
UPD:
For variables can use eval, but this not secure and useless. Do not use this, it's just for demonstration.
var x1 = 0;
var x2 = 0;
var x3 = 0;
$('.btn').on('click', function(){
var vn = $(this).data('varname');
var ps = $(this).data('panel-selector');
eval(vn + '+=1');
$(ps).text(eval(vn));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn" data-varname='x1' data-panel-selector='#panel1'>#btn1</button>
<button class="btn" data-varname='x2' data-panel-selector='#panel2'>#btn2</button>
<button class="btn" data-varname='x3' data-panel-selector='#panel3'>#btn3</button>
You can add every button HTML onclick event and create one function.
function add() {
this.innerHTML(parseInt(this.innerHTML()) + 1);
}
<button onclick=add()>1</button>
<button onclick=add()>1</button>
<button onclick=add()>1</button>

How to update fields dynamically in Javascript?

<button onclick="myFunction()">Set demo1</button>
<button onclick="myFunction()">Set demo2</button>
<button onclick="myFunction()">Set demo3</button>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
This is the markup I have. I am trying to use just one function to update the <p> tags individually.
Example Scenario: Clicking Set demo1 button will only update the <p> which has id="demo1" but with only one function.
Help would be very much appreciated.
You can use following approach. Clicking on each button will affect corresponding p element.
var elems = document.getElementsByClassName('btn');
Array.from(elems).forEach(v => v.addEventListener('click', function(){
var index = this.innerHTML.match(/\d+/)[0];
var elem = document.getElementById('demo'+index);
// logic
elem.style.color = 'red'; // just an example
}));
<button class='btn'>Set demo1</button>
<button class='btn'>Set demo2</button>
<button class='btn'>Set demo3</button>
<p id="demo1">1</p>
<p id="demo2">2</p>
<p id="demo3">3</p>
If you change your markup slightly so that each button has a data-target attribute, then it can be easily done.
HTML:
<button onclick="myFunction()" data-target="#demo1">Set demo1</button>
<button onclick="myFunction()" data-target="#demo2">Set demo2</button>
<button onclick="myFunction()" data-target="#demo3">Set demo3</button>
JS
function myFunction() {
var pTag = document.getElementById(this.getAttribute('data-target'));
pTag.textContent = "Hello world"; // whatever you would like
}

jQuery .click() function isn't working

My jQuery .click() function isn't working - it has to add text of button to string x and set totaldiv.text() to x, but when I click button it does nothing.
$(document).ready(function() {
var x = "", y = "";
var operator;
var totaldiv = $("#total");
totaldiv.text("0");
$("#numbers button").click(function(){
x += $(this).text();
totaldiv.text(x);
});
});
My html if it's needed:
<div id="numbers">
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
<button class="btn">5</button>
<button class="btn">6</button>
<button class="btn">7</button>
<button class="btn">8</button>
<button class="btn">9</button>
<button class="btn">0</button>
</div>
<div id="total">
</div>
Well if you mean why is it adding the number on so 2, 3, 4 would be 234 instead of 9. It's because they are strings.
use this line instead...
var x = 0;
x += parseInt($(this).text());
otherwise it works if you include jQuery as said in the comments

How to build a click counter with multiple click values and combine them into a total click value?

I am a newbie and I built this click counter with jquery and it is working great but it seems clunky to me and I want to make my code cleaner. So my question is how can I combine the two click functions into one function and then use the total of the two variables "click1" and "click2" as the value for the variable "sum"? I am assuming one would loop through the separate elements and add their clicks to an array and then add the values stored in the array and assign that as the total, but I am not sure where to start or if that is even possible. I am learning jquery and plain javascript so I can understand suggestions in either syntax. Thank you all!
CODEPEN: http://codepen.io/chasereckling/pen/KgArLG?editors=1010
<div class="clickButton">
<button id="updateClick1" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber">0</span></span>
</div>
<div class="clickButton">
<button id="updateClick2" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber">0</span></span>
</div>
<div>Total Clicks: <span id="sumClicks">0</span></div>
<script>
var count1 = 0;
var count2 = 0;
var sum = 0;
$('#updateClick1').click(function() {
count1++;
sum++;
$(this).siblings().children('.clickNumber').html(count1);
$('#sumClicks').html(sum);
});
$('#updateClick2').click(function() {
count2++;
sum++;
$(this).siblings().children('.clickNumber').html(count2);
$('#sumClicks').html(sum);
});
</script>
You can do something like this:
var sum = 0;
function clickHandler () {
var $target = $(this),
$span = $target.siblings("span").children(".clickNumber"),
$sum = $("#sumClicks");
$span.text(parseInt($span.text()) + 1);
sum += 1;
$sum.text(sum);
}
$('button[type="button"]').click(clickHandler);
Here is codepen:
sum of clicks
Check the following code snippet
var count=0;
var sum = 0;
var $sumElement=$('#sumClicks');
sum=parseInt($sumElement.html());
$(document).ready(function(){
$('button').click(function() {
var element=$(this);
var $clickCount=$(this).siblings().children('.clickNumber');
var clickCountVal=parseInt($clickCount.html());
clickCountVal++;
sum++;
$clickCount.html(clickCountVal);
$sumElement.html(sum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clickButton">
<button id="updateClick1" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber">0</span></span>
</div>
<div class="clickButton">
<button id="updateClick2" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber">0</span></span>
</div>
<div>Total Clicks: <span id="sumClicks">0</span></div>
Hope this helps
You could try something like this, it'll be a bit cleaner:
<div class="clickButton">
<button id="updateClick1" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber1">0</span></span>
</div>
<div class="clickButton">
<button id="updateClick2" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber2">0</span></span>
</div>
<div>Total Clicks: <span id="sumClicks">0</span></div>
var count = [0,0];
$('#updateClick1').click(function() {
count[0]++;
$('.clickNumber1').html(count[0]);
$('#sumClicks').html(count[0] + count[1]);
});
$('#updateClick2').click(function() {
count[1]++;
$('.clickNumber2').html(count[1]);
$('#sumClicks').html(count[0] + count[1]);
});
JSFIDDLE: https://jsfiddle.net/s7pw5oqs/1/

Categories

Resources