How to sum a number in sequence after click a button? - javascript

$(document).ready(function(){
var current = 0;
current += 4;
$('.add').click(function(){
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>
i want to sum a number in sequence after click the add button like the above snippet, so the results will be 4 8 12 16 18 and so on. Teach me how to do this ?

Try this: Your increment should be in the click function as well. SO the increment actually occurs when you click, if it's outside, it won't occur.
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});

You have to increment in click handler. Right now it is getting incremented only once.
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>

You need to move the line current += 4; to inside the click function . so only you can increment the value on click .otherwise you will get 4 for every click.
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>

Move count inside click function.
$(document).ready(function() {
var current = 0;
$('.add').click(function() {
current += 4;
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>

Try this:
The key is to grab the current value, add 4 to it and then replace that value with the new sum.
$(document).ready(function(){
$('.add').click(function(){
var existing = parseInt($("#result").text());
$('.box').text(existing + 4);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div id ="result" class="box">
0
</div>

Try this one. Get the box value and next check value is numeric if true then add 4 and bind value in div.
$('.add').click(function () {
var current = $('.box').text();
if ($.isNumeric(current))
$('.box').html(parseInt(current)+4);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div id ="result" class="box">
0
</div>

Move Current variable inside the click function..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
</script>
<button class="add">add</button>
<div class="box">
0
</div>

working example
It is very simple, you just need to use loop and a array variable. set limit according to your requirement.
<html>
<body>
<script type="text/javascript">
$(document).ready(function(){
var current = 0;
var c=0;
var res = [];
$('.add').on('click', function(){
for (c = 0; c < 3; c=c+1){
current += 4;
res[c] = current
$('.box').html('&nbsp'+res);
}
});
});
</script>
<button class="add">add</button>
<div class="box">
</div>
</body>
</html>

Related

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>

I can't make this JavaScript count working

I want to make a button (out of divs) and a paragraph (or any text field) below the divs that counts the clicks.
$(document).ready(function() {
$('#butt').mousedown(function() {
$("#butt").hide();
});
$("#pushed").mouseup(function() {
$("#butt").show();
});
$("#butt").click(function() {
button_click();
});
});
var clicks = 0;
function button_click() {
clicks = parseInt(clicks) + parseInt(1);
var divData = document.getElementById("showCount");
divData.innerHTML = "Clicks:" + clicks;
}
<!-- <link type="text/css" rel="stylesheet" href="CSS.css"/> -->
<form name="ButtonForm">
<div id="container">
<div id="pushed"></div>
<div id="butt"></div>
</div>
<div id="showCount"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<!--<script src="Untitled-1.js" type="text/javascript"></script>-->
</form>
Your div elements are empty and there is no CSS to give them any explicit size, so they will never be visible for you to click on them.
Also, the mousedown event handler can and should be combined with the click handler for butt and the mouseup event handler should just be a click event as well.
Additionally, you only need to update the number of clicks, not the word "Clicks", so make a separate placeholder for the number with a span element and then you can hard-code the word "Clicks" into the div.
Lastly, to increment a number by one, you can just use the pre or post-increment operator (++).
$(document).ready(function() {
var clicks = 0;
var divData = $("#clickCount");
$("#pushed").on("click", function() {
$("#butt").show();
});
$("#butt").on("click", function() {
$("#butt").hide();
clicks++; // increment the counter by one
divData.html(clicks);
});
});
#pushed, #butt {height:50px; width:150px; background-color:green; margin:5px;}
<body>
<form name="ButtonForm">
<div id="container">
<div id="pushed"></div>
<div id="butt"></div>
</div>
<div id="showCount">Clicks <span id="clickCount"></span></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
</form>
</body>
First of all, you should simplify your code. Hiding and showing the button is not necessary to produce the result you are looking for.
Second, change the #butt element to an actual button so that you have something to see and click.
Third, make sure your script is loading after jquery is included.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<button id="butt">I'm a button</button>
<div id="showCount"></div>
<script>
$(document).ready(function() {
$("#butt").click(function() {
button_click();
});
var clicks = 0;
function button_click() {
clicks = parseInt(clicks) + parseInt(1);
var divData = document.getElementById("showCount");
divData.innerHTML = "Clicks:" + clicks;
}
});
</script>

add div using appendChild

This code is supposed to be looping and adding multiple divs, but it isn't working. When I click it, only one div appears. If I click again, nothing happens.
<body>
<div class="start" >
<div id = "coba">
</div>
<div id = "cobi">
</div>
</div>
<script>
var divs = document.getElementById("coba").addEventListener("click", function () {
for (var i = 1; i < 100; i++) {
var di = document.createElement('div');
document.getElementById('coba').appendChild(di);
}
});
</script>
</body>
Thanks for your help
Your code does not work because you did not do anything with the variable "i" in the for statement. If you look at the fiddles of user2181397 & meghan Armes you will see how they added a line in the script to put it to work.
I tested the below in my IDE and it works just fine:
<body>
<div class="start" style="margin-top:50px; color:black;">
<div id = "coba">
<p>Click Me</p>
</div>
<div id = "cobi">
</div>
</div>
<script>
var divs = document.getElementById("coba").addEventListener("click", function() {
for (var i = 1; i < 100; i++) {
var di = document.createElement('div');
di.innerHTML=i;
document.getElementById('coba').appendChild(di);
}
});
</script>
</body>

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/

Pass js var into html block being added via appendTo

I've got this html which i'm injecting into the page when someone clicks a button. The html gets appended again each time the button is clicked using the js below.
<div style="display: none;">
<div class="grab-me">
<p>This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
});
});
But what i need to do is where it says "This is fieldset 1" i need to increase that number by 1 each time so subsequent appends say This is fieldset 2, This is fieldset 3 etc etc. I can't see how i can pass a variable (my count var) in to the html block when it gets cloned that will replace that number.
Here is a jsfiddle of it: http://jsfiddle.net/tzbgA/
Any help would be great! Thanks!!
you can give the sentence you want to change class. Then using jQuery selectors change the text inside it.
<body>
<button class="add-member">add more</button>
<div style="display: none;">
<div class="grab-me">
<p class="count">This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
<div id="register">
</div>
</body>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register')
.find('p.count').html('This is fieldset '+count);
count += 1;
});
});
add span:
<p>This is fieldset <span>1</span></p>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
$('.span').html('count');
});
});
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me').clone();
$(grab p).html('This is fieldset '+count).appendTo('#register');
});
});
Fiddle: http://jsfiddle.net/howderek/tzbgA/2/
Here's a version that uses 8 lines of code:
Code (Javascript)
var count = 1,
html = ' <p>This is fieldset #</p><input name="foo[]"/> <input name = "bar[]"/> <input name = "oth[]"/>';
$(function () {
$('.add-member').live("click", function (e) {
e.preventDefault(e);
document.getElementById("register").innerHTML += html.replace("#",++count);
});
});

Categories

Resources