How to get the pressed button in a function - javascript

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>

Related

How to target a button from a group of buttons in JQuery without a class name or id

How can I target a button from a group of buttons without using a class or id, just n JQuery
Example:
<body>
<button>Click Me</button>
<button>Click Me</button>
<button class="food">Click Me</button>
<button>Click Me</button>
<button>Click Me</button>
<input type="text">
<!--
<script src="ajax.googleapis.com/ajax/libs/jquery/3.6.0/…>
<script src="index.js"></script>
-->
</body>
With JQuery this would only be possible if the button's had unique innerText or innerHTML that you could then predict.
Using my example HTML from below:
<div>
<button>Button1</button>
<button>Button2</button>
<button>Button3</button>
<button>Button4</button>
</div>
You would need to use JQuery to grab all tags, and then filter that by their innerHTML or innerText depending on what is inside the button tag.
See the below JS:
// Assuming you want 'Button 1'
for(let el of $("button")){
if(el.innerText === 'Button1') el.addEventListener() // Then from here do the rest
}
There many ways, You can use onclick method inline Html. A crude way---
<script>
function function1(){
alert ('Button1')
}
function function2(){
alert ('Button2')
}
function function3 (){
alert ('Button3')
}
</script>
</head>
<body>
<button onclick="function1()">Button 1</button>
<button onclick="function2()">Button 2</button>
<button onclick="function3()">Button 3</button>
</body>

how to access the id of any button on click?

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>

several eventhandler in one function

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

Multiple buttons with same class in jQuery

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.

How to get prev textarea element

I want to get a text from a textarea after clicking on button that is next to the textarea.
The problem is that I will have many textareas and every button must returns the text of the textarea that corresponds to it.
This is my code
function btnmodif(){
var mod = $(this).prev().val();
alert(mod);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="list-item-edit">
<textarea class="list_input">eggs</textarea>
<button class="btn btn-modify-item" onClick="btnmodif()">get text</button>
</div>
<div class="list-item-edit">
<textarea class="list_input">water</textarea>
<button class="btn btn-modify-item" onClick="btnmodif()">get text</button>
</div>
You have to pass object clicked to btnmodif function.
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
JS
function btnmodif(button){
var mod = $(button).prev().val();
alert(mod);
};
Also, you should use .prev function.
Read more about .prev() function, here.
function btnmodif(button){
var mod = $(button).prev().val();
alert(mod);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="list-item-edit">
<textarea class="list_input">eggs</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
<div class="list-item-edit">
<textarea class="list_input">water</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
Firstly, you need to pass the clicked element as context to the function:
onClick="btnmodif(this)"
...
function btnmodif(button){
Second, if the HTML structure will remain the same (i.e. the textarea is always going to be the element immediately before the button), then you can use prev()
var mod = $(button).prev('textarea').val();
https://api.jquery.com/prev/
If that structure isn't guaranteed to be maintained, then .siblings() gives you a bit more flexibility, as it searches through all the elements at the same hierarchical level in the DOM to find what you want:
var mod = $(button).siblings('textarea').val();
https://api.jquery.com/siblings/
Here is what are you looking for.
Add this as parameter to your button.onclick
Thanks to jQuery:
Using $(element).parent(), you get your div element.
Using $(element).parent().find('.list_input'), you get your textarea element.
Using $(element).parent().find('.list_input').text() gives you the value of the textarea "related to" the clicked button.
function btnmodif(element){
var result = $(element).parent().find('.list_input').text();
alert(result);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="list-item-edit">
<textarea class="list_input">eggs</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
<div class="list-item-edit">
<textarea class="list_input">water</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
You're missing the this from the inline handler specification:
https://jsfiddle.net/3mvod6ux/
Use siblings with a selector to get the textarea's value that belong to the same block of the button clicked.
function btnmodif(button){
var mod = $(button).siblings("textarea").val();
alert(mod);
};
Another way to do this task .
Instead to use HTML event attribute this is better approach.
var btnModifyItem = $('.btn-modify-item');
btnModifyItem.click(function(){
var mod = $(this).prev().val();
alert(mod);
})
This way you can get the parent of button (and textarea) and then can get the text from child textarea:
$('button').on('click', function () {
console.log(($(this).parent().find("textarea").text()));
});

Categories