get value from multiple buttons - javascript

How can I get the value of the button that the user clicked. I tried this but it doesn't work
for (var i = 0; i < 4; i++) {
var x = document.getElementsByClassName("button")[i].onclick() = function(){
console.log(x);
}
}

$("button").click(function() {
alert($(this).html()); // for the text in button tag. for value in button tag use $(this).val()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="up" value="up">button up</button>
<button id="down" value="down">button down</button>
if you don't want to use jquery and use only pure javascript you can do following:
<button id="up" value="up" onclick="alert(this.value)">button up</button><!-- for value -->
<button id="down" onclick="alert(this.innerHTML)">button down</button><!-- for text in tag -->

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

How to get the button's id value with my js?

A simple html structure.
<button id="b1">b1</button>
<button id="b2">b2</button>
<button id="b3">b3</button>
Add event listener to buttons.
var bs = document.getElementsByTagName('button');
for(var i = 0; i < bs.length; i++){
bs[i].addEventListener("click", getInfo);
}
How to write getInfo function to output button's id when clicked?
function getInfo() {
}
Only one thing you need to do is to pass the event value to your getInfo functoin.
There's an example below:
var bs = document.getElementsByTagName('button');
for(var i=0;i<bs.length;i++){
bs[i].addEventListener("click",getInfo);
}
function getInfo(e){
alert(e.target.id);
}
<button id="b1" >b1</button>
<button id="b2" >b2</button>
<button id="b3" >b3</button>

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

Categories

Resources