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

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>

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

Calculate numbers on click [closed]

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

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

$(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>

access the exact view in a raw using js

My view has a button and the view is looped.so it has raws.
when i click the button of a single raw i need to color that button.
so i added a onclick="select_Button(<?php echo $rawID?>)" to the raw's button in my view
select_Button is my funtion in js
function select_Button(rawNumberOfVote) {
var RawNumber = rawNumberOfVote;
alert ("Form submitted successfully" + RawNumber);
var upVote = document.getElementById("up_vote");
upVote.style.background = "green";
}
like above i send the rawID to the funtion.
how can i edit this line to accept the view called up_vote in that particular raw id that i got from parameter.
var upVote = document.getElementById("up_vote");
becuz if i only use this line it will color the first raw's button instead the one i wanted
Thank you
you can use data attribute in your html referencing to this page and this page. and retraive with this this jquery code snippet:
$("[data-test ='my value']")
or this code snnipet in javascript:
document.querySelectorAll(".example").find(function(dom){
return dom.dataset.test == "expected-value"
});
Update:
accourding to this page querySelectorAll return nodeList and NodeList are not array and we cannot use find method so I change my answer to this code:
<html>
<body>
<div class="post" data-key="1">
<lable>test</lable>
<button type="button" onclick="upvote(1)">up vote</button>
</div>
<div class="post" data-key="2">
<lable>test</lable>
<button type="button" onclick="upvote(2)">up vote</button>
</div>
<div class="post" data-key="3">
<lable>test</lable>
<button type="button" onclick="upvote(3)">up vote</button>
</div>
</body>
</html>
<script type="text/javascript">
var upvote = function(id) {
var nodes = document.querySelectorAll(".post");
console.log(nodes.length);
for(i = 0 ; i < nodes.length ; i++){
console.log(nodes[i].dataset.key);
if (nodes[i].dataset.key == id)
nodes[i].style.backgroundColor = "red";
}
};
</script>

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