I have multiple buttons with the same class on my page, now when I try to call a method on the click event of the button, that method executes for all of the buttons because they have the same class.
The buttons on my page are dynamically created so I cant give different class to each button.
I am looking for a way to only execute some particular method on the click of the first element with the given class.
By using Jquery's .first() function, you can get the first element and then only bind the click event to it.
$(".sameClass").first().on("click", function() { console.log("clicked"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="sameClass">Button 1</button>
<button class="sameClass">Button 2</button>
<button class="sameClass">Button 3</button>
Here it is:
$("button").each(function(i, item) {
if(i === 0) {
$(item).on("click", function() {
console.log('works only for the first button');
})
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class"test-class">btn 1</button>
<button class"test-class">btn 2</button>
<button class"test-class">btn 3</button>
<button class"test-class">btn 4</button>
<button class"test-class">btn 5</button>
I'm looping through all buttons and adding event listener only for the first of them.
Related
Is it possible to create a function that returns which button was pressed, even though all buttons have the same class?
It is important that the classes of the buttons must not be changed.
<html>
<body>
<button class="button">text</button>
<button class="button">text</button> //this button was clicked
<button class="button">text</button>
</body>
</html>
The code is only for visualisation I know it isn't right.
function myfunction(){
console.log(clickedbutton)
}
What I have to fill in so the code runs?
Sorry for the bad code i don't know how to make it more clearly.
Hello and happy new 2021!
I think this might be a slight duplicate of this.
As Gabriele said, you can get the HTML element by using the target. If you need some logic for differentiating the structures (using them in some state later on), you would need to assign an id or a different class.
Delegate
document.getElementById("buttonDiv").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("button")) console.log(tgt.textContent,"clicked")
})
<div id="buttonDiv">
<button class="button">text 1</button>
<button class="button">text 2</button>
<button class="button">text 3</button>
</div>
When an event happens and the handler that is bound to that event for that element is called, it is passed the event as the first parameter. And one of the properties of the event is the target which points to the element that triggered the event.
so
function clickHandler(event) {
const clickedElement = event.target;
console.log(clickedElement.textContent);
}
document
.querySelectorAll('.button')
.forEach(button => button.addEventListener('click', clickHandler))
<button class="button">text 1</button>
<button class="button">text 2</button>
<button class="button">text 3</button>
If you assign a function to the onClick event of a button (or multiple buttons), you can receive the event info as an argument, like so:
function myfunction(e) {
console.log(e.target.id)
}
<!DOCTYPE html>
<html>
<body>
<button id="button-1" class="button" onclick="myfunction(event)">text</button>
<button id="button-2" class="button" onclick="myfunction(event)">text</button>
<button id="button-3" class="button" onclick="myfunction(event)">text</button>
</body>
</html>
You can make use of data-id for getting index of button clicked.
const button = document.querySelectorAll(".button");
function getClickedIndex(evt) {
console.log(evt.target.getAttribute("data-id"));
}
button.forEach(button => button.addEventListener('click', getClickedIndex))
<html>
<body>
<button class="button" data-id="1">text</button>
<button class="button" data-id="2">text</button>
<button class="button" data-id="3">text</button>
</body>
</html>
I have a button as such whose id I am not aware of
<button id="" class="mybtn" type=""></button>
and now I want to get the id of this button on click
("//what to write here").click(){
console.log($(this).id);//something like this i want
}
but the problem with using class selector is that I have multiple buttons which so it will select all of them and not just the one which is clicked.
You can do it like this. I commented the code for the syntax
$("button.mybtn").on("click", function() {
console.log($(this).attr("id")); // return blank when no id
console.log(this.id); // return undefined when no id
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="hello" class="mybtn" type="">Sample</button>
<button id="hello1" class="mybtn" type="">Sample</button>
The event handler below is attached to all buttons (elements) with the class .btn but since you can only click one button at a time, you will only see one id per click - the id of the button clicked:
$('.mybtn').on('click', function() {
console.log( this.id );
});
$(function() {
$('.mybtn').on('click', function() {
console.log( this.id );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="id1" class="mybtn" type="">Button 1</button>
<button id="id2" class="mybtn" type="">Button 2</button>
<button id="id3" class="mybtn" type="">Button 3</button>
<button id="id4" class="mybtn" type="">Button 4</button>
Instead of creating a new function for every button handler i wanna create just one function and handle all the buttons there.I wanna the first button to do something different than the second one....My idea was to have one eventlistener but how do i know the target.id is the same as btn1 for example?
<div class="col-11" id="btns">
<button class="btn btn-dark" id="btn1">Button 1</button>
<button class="btn btn-dark" id="btn2">Button 2</button>
<button class="btn btn-red" id="btn3">Button 3</button>
<button class="btn btn-blue" id="btn4">Button 4</button>
</div>
let btn1=document.getElementById('btns');
btn1.addEventListener("click",doStuff);
function doStuff(e){
if(e.target.id===document.getElementById('btn1')){ //doesnt work
console.log("Hello");
}else if(e.target.id===.getElementbyId('btn2'){
//doSomething...
}
}
You have the right approach, there's just an error in your code:
e.target.id===document.getElementById('btn1')
This compares the ID of the element that was clicked to the element with the ID of 'btn1'.
That is, it compares a string to an element.
Naturally, this will always return false.
Instead, try:
e.target===document.getElementById('btn1')
This compares an element to an element.
Or:
e.target.id==='btn1'
This compares a string to a string.
Optional: You could simplify your code by using a switch/case block instead of a bunch of if statements. Here's how I would write your click handler:
function doStuff(e) {
switch(e.target.id){
case 'btn1':
// Do something for btn1...
break;
case 'btn2':
// Do something for btn2...
break;
}
}
More information about switch/case: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
Suppose there are 5 buttons.
When each button clicks, it shows the alert box of the button's value. For instance, when I click Button 2, it shows the alert box of "You click Button 2"; when I click Button 4, it shows the alert box of "You click Button 4."
Below is the traditional way to practice it:
<script>
$(function(){
$("#b0").click(function(){
alert("You click Button 0");
});
$("#b1").click(function(){
alert("You click Button 1");
});
$("#b2").click(function(){
alert("You click Button 2");
});
$("#b3").click(function(){
alert("You click Button 3");
});
$("#b4").click(function(){
alert("You click Button 4");
});
});
</script>
<button id="b0">Button 0</button>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="b4">Button 4</button>
But it is too inefficient and unprofessional, so I changed it like below:
<script>
$(function(){
for(i=0;i<5;i++){
$("#b"+i).click(function(){
alert("You click Button "+i);
});
}
});
</script>
<button id="b0">Button 0</button>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="b4">Button 4</button>
After changing, it always shows "You click Button 5." How can I solve this question using for loop?
You are always firing the value of variable i, after the for loop the value will be 5. So use a self calling function with argument i.
$(function() {
for (i = 0; i < 5; i++) {
(function(i) {
$("#b" + i).click(function() {
alert("You click Button " + i);
});
})(i);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="b0">Button 0</button>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="b4">Button 4</button>
Or in latest browser use let for block scope level local variable value
$(function() {
"use strict";
for (let i = 0; i < 5; i++) {
$("#b" + i).click(function() {
alert("You click Button " + i);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="b0">Button 0</button>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="b4">Button 4</button>
Or you can use index() method and attribute start selector
$(function() {
var $sel = $('[id^=b]');
$sel.click(function() {
alert("You click Button " + $sel.index(this));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="b0">Button 0</button>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="b4">Button 4</button>
Alternatively you can use jQuery attribute selector
$("button[id^='b']" ).click(function(){
alert("You click Button " + this.id.substring(1));
});
Here is my live demo: https://jsfiddle.net/johndoe1992/3uqg7y9L/
When I click some button on the left panel it must be cloned to the right panel (see live demo)
The bootstrap class 'disable' must be added on click to this button from the left panel too. We have the disabled button on the left and the enabled button on the right
When I click some button on the right panel it must relocate back to the left panel (see live demo)
We have the enabled button on the left and no button on the right
I've tried to find a solution using this, which works for #1 and #2, but I have no idea what to do with #3
$(this).clone().appendTo('.selected');
$(this).prop('disabled', true);
Thank you for your help
Firstly you need to use a delegated event handler to handle clicks on the buttons you dynamically add to the .selected div.
Secondly you need to add a way of identifying which button was clicked on in the .selected div and matching that with the original in the .base div. To do that you could use a data attribute. From there you can just set the disabled property state and remove() the clone. Something like this:
<div class="base">
<button type="button" class="btn btn-default" data-state="default">Text 1</button>
<button type="button" class="btn btn-primary" data-state="primary">Text 2</button>
<button type="button" class="btn btn-info" data-state="info">Text 3</button>
<button type="button" class="btn btn-warning" data-state="warning">Text 4</button>
<button type="button" class="btn btn-success" data-state="success">Text 5</button>
<button type="button" class="btn btn-danger" data-state="danger">Text 6</button>
</div>
<div class="selected"></div>
$(document).on('click', '.btn', function() {
if($(this).parent().attr("class") == "base") {
$(this).clone().appendTo('.selected');
$(this).prop('disabled', true);
}
else {
$('.base').find('[data-state="' + $(this).data('state') + '"]').prop('disabled', false);
$(this).remove();
}
});
Updated fiddle