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

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>

Related

get value from multiple buttons

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

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
}

(One button creates one element) multiple times

I'm trying to have a setup where there are multiple buttons that each add one element (and one only) to a list (further down my webpage) + disables the button which was just clicked (but not the other buttons). Moreover, if you click on the corresponding element that was created, it deletes itself and enables the corresponding button back.
I managed to do it for one instance of a button, with the following code :
Javascript :
var btn1 = document.getElementById('btn1')
, sortie = document.getElementById('sortie');
function createSortie() {
var d = document.createElement("span");
d.id = "sortieBtn1";
d.className = "label label-success";
d.onclick = removeSelf;
d.innerHTML = "Hey, sup', now click on me to make me disappear";
sortie.appendChild(d);
}
function removeSelf() {
document.getElementById('sortieBtn1').remove();
document.getElementById('btn1').disabled = false;
}
function modifyButton(a) {
document.getElementById(a).disabled = true;
}
HTML :
<button class="btn btn-primary" id="btn1" onclick="createSortie();modifyButton(this.id)">Click on me to create a new element</button><br />
<br/>
<br/>
Sortie :
<div id="sortie"></div>
Example : http://www.codeply.com/go/SEL7ZqBI49
I now want it for multiple buttons, I could of course do something like this, but there are smarter ways to do achieve what I need (*), namely, more buttons and obviously, without having designated functions for each pair of button/created element.
(*) : maybe - but not mandatory - with something similar to function factories in R ?
Any idea on how to achieve that ? Thanks.
You can actually pass the reference to the clicked button as a parameter to the onclick function which makes things lots easier than trying to work with ids. Also, you won't have to find the elements every time and thus you can apply to as many items as you want. Check a working example:
var btns = document.getElementsByClassName('.btn'),
sortie = document.getElementById('sortie');
// Creates the labels on the output div when a button is clicked
function createSortie(button) {
// Create a label using a <span> element
var label = document.createElement("span");
// The ID will not be used but it's useful to link it to the
// originating button in some way
label.id = "sortie" + button.id;
label.className = "label label-success";
// Set click handler on the label
label.onclick = function() {
// Remove itself, using self-reference as argument
removeLabel(label);
// Toggle the originating button to enabled again
// (disabled = false)
toggleButton(button, false);
};
label.innerHTML = "I''m label for " + button.id;
// Set button to disabled
toggleButton(button, true);
// Add this label to sortie
sortie.appendChild(label);
}
// Removes a label, passed as parameter
function removeLabel(label) {
label.remove();
}
// Toggles a button ON or OFF, as specified on the state parameter
function toggleButton(button, state) {
button.disabled = state;
}
.label {
cursor: pointer;
display: block;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<h3>Buttons</h3>
<button class="btn btn-primary" id="btn1" onclick="createSortie(this);">Element 1</button>
<br />
<button class="btn btn-primary" id="btn2" onclick="createSortie(this);">Element 2</button>
<h3>Sortie :</h3>
<div id="sortie">
</div>
I also forked your Codeply: http://www.codeply.com/go/cJwYL0iBeY
Feel free to ask anything.
If you use classes for the buttons, and then use a number in the ID's, it would be easy to target the sortie belonging to each button, something like
var buttons = document.getElementsByClassName('btn');
for (var i=0; i<buttons.length; i++) {
buttons[i].addEventListener('click', btnClick);
}
function btnClick() {
var sortie = document.getElementById('sortie' + this.id.replace('btn',''));
createSortie(sortie, this);
}
function createSortie(sortie, button) {
var d = document.createElement("span");
d.className = "label label-success";
d.addEventListener('click', function() {
button.disabled = false;
this.remove();
});
d.innerHTML = "Hey, sup', now click on me to make me disappear";
sortie.appendChild(d);
button.disabled = true;
}
<button class="btn btn-primary" id="btn1">Click on me to create a new element</button><br />
<br/><br/>
Sortie :
<div id="sortie1"></div>
<br/><br/>
<button class="btn btn-primary" id="btn2">Click on me to create a new element</button><br />
<br/><br/>
Sortie :
<div id="sortie2"></div>
<br/><br/>
<button class="btn btn-primary" id="btn3">Click on me to create a new element</button><br />
<br/><br/>
Sortie :
<div id="sortie3"></div>
I created a fiddle for you, it is mostly based on relative selection and not on IDs, i pass the whole element in function and then do further action on that basis, have a look
Fiddle
HTML
<div>
<button class="btn btn-primary" id="btn1" onclick="createSortie(this);modifyButton(this)">Click on me to create a new element</button><br />
<br/>
<br/>
Sortie :
<div class="sortie"></div>
</div>
<div>
<button class="btn btn-primary" id="btn1" onclick="createSortie(this);modifyButton(this)">Click on me to create a new element</button><br />
<br/>
<br/>
Sortie :
<div class="sortie"></div>
</div>
JS
function createSortie(elem) {
elem.parentElement.querySelector('.sortie').innerHTML+='<span class="label label-success" onclick="removeSelf(this)">Hey, sup, now click on me to make me disappear</span>';
}
function removeSelf(ele) {
console.log( ele.parentElement.parentElement.querySelector('button'));
ele.parentElement.parentElement.querySelector('button').removeAttribute('disabled')
ele.remove();
}
function modifyButton(ele) {
ele.setAttribute('disabled','disabled')
}

Get value from THIS element that shares class in javascript?

So the app I'm making is pulling data from a json file and rendering the data dynamically. I'm using classes because I don't think I should pull an ID name from the json file to be added into the html element.. (or should I?) - How do I get querySelector to get the value from the one I click on? And not from every element that has the same class?
<button class="playBtn" value="{{filename}}"></button>
<button class="playBtn" value="{{filename}}"></button>
<button class="playBtn" value="{{filename}}"></button>
<button class="playBtn" value="{{filename}}"></button>
<button class="playBtn" value="{{filename}}"></button>
var selectedSong = document.querySelector('.playBtn').value;
json to Button Value to onClick send value to be a new Variable
If i understands you properly...
Something like this should help
Here you just listen for clicks on all playBtn, but gets value from the one you click.
document.addEventListener('click', function(event) {
var button;
button = event.target;
if (button.classList.contains('playBtn')) {
console.log(button.getAttribute('value'));
}
});
<button class="playBtn" value="{{filename}}"></button>
<button class="playBtn" value="{{filename}}"></button>
<button class="playBtn" value="{{filename}}"></button>
<button class="playBtn" value="{{filename}}"></button>
<button class="playBtn" value="{{filename}}"></button>
var play = document.getElementsByClassName('playBtn');
for(var i=0, len=play.length; i<len; i++){
(function(index){
play[i].onclick = function(){
alert(play[index].value);
}
})(i);
}
<button class="playBtn" value="one">button one</button>
<button class="playBtn" value="two">button two</button>
<button class="playBtn" value="three">button three</button>
<button class="playBtn" value="four">button four</button>
<button class="playBtn" value="five">button five</button>
Vanilla JS
document.querySelectorAll returns a NodeList so we need to iterate over that collection and apply the event listener to each element in it. By extending the NodeList prototype we can add our own little function to add any event to each node. We then have ourselves a nice jQueryesq method to use it:
NodeList.prototype.on = function(event,func) {
[].forEach.call(this, function (el) {
el.addEventListener(event, func, false);
});
return this;//return self to maintain chainability
};
//to listen for a click on each of these:
document.querySelectorAll('.playBtn').on('click',function(){
alert(this.value);
});
You can even chain these events like this:
document.querySelectorAll('.playBtn').on('mouseover',function(){
this.style.borderColor='red';
}).on('mouseout',function(){
this.style.borderColor='';
});
Here's the demo jsFiddle and snippet:
NodeList.prototype.on = function(event,func) {
[].forEach.call(this, function (el) {
el.addEventListener(event, func, false);
});
return this;//return self to maintain chainability
};
document.querySelectorAll('.playBtn').on('click',function(){
alert(this.value);
return false;
});
document.querySelectorAll('.playBtn').on('mouseover',function(){
this.style.borderColor='red';
}).on('mouseout',function(){
this.style.borderColor='';
});
<button class="playBtn" value="a">A</button>
<button class="playBtn" value="b">B</button>
<button class="playBtn" value="c">C</button>
<button class="playBtn" value="d">D</button>
<button class="playBtn" value="e">E</button>
With jQuery
Of course if jQuery is available to you then all this is baked in. It doesn't directly answer your question of "How do I get querySelector to get the value from the one I click on?" because it's not directly using querySelector but it does do what you need:
$(function(){//wait for document ready
$(".playBtn").on("click",function(){
alert($(this).val());
});
})
Demo jsFiddle
$(function(){
$(".playBtn").on("click",function(){
alert($(this).val());
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="playBtn" value="a">A</button>
<button class="playBtn" value="b">B</button>
<button class="playBtn" value="c">C</button>
<button class="playBtn" value="d">D</button>
<button class="playBtn" value="e">E</button>
document.querySelector() will return only the first found node. document.querySelectorAll would return a list that you would need to iterate.
However, this can be done with jQuery easily:
var selectedSong = '';
$('.playBtn').on('click', function()
{
selectedSong = $(this).val();
});
See fiddle.
Or with pure JS using getElementsByClassName or querySelectorAll
var selectedSong = '';
var a_btn = document.getElementsByClassName('playBtn');
// or querySelectorAll
// var a_btn = document.querySelectorAll('.playBtn');
for(var i = 0; i < a_btn.length; i++)
{
a_btn[i].onclick = function() {
selectedSong = this.value;
};
};
See fiddle.

Categories

Resources