1

I have a two buttons with the same selector class. When I do this:

$('.my_button').click(function() {
    console.log(1);
});

, and then click on the button it log 1 two times, like I clicked both buttons instead single. So my question is: There exists some way in JS to get only that button what I clicked, without assign unique selector like id. I am newbien in JS, so can somebody explain me? I found related issue here. Thanks!

Edit:

I make buttons a little bit different. And yes, it returns only single button, but why click trigger works two times. Console log log two times.

Community
  • 1
  • 1
nowiko
  • 2,507
  • 6
  • 38
  • 82

6 Answers6

4

Every event listener receives the event, which carries the event target. Try the below example.

$('.my_button').click(function(e) {
    console.log(e);
    console.log(e.currentTarget);
    console.log($(e.currentTarget));
});
Mjh
  • 2,904
  • 1
  • 17
  • 16
3

use this inside your function code

$('.my_button').on('click',function() {
    var tempContainer=$(this).parent();
    alert($(tempContainer).html());   // you ll see that you are showing the code where exists your clicked button
});
Med.Amine.Touil
  • 1,225
  • 2
  • 11
  • 15
3

Assign different id to your buttons

$(".my_button").on("click",function(){
  console.log($(this).attr("id"))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="button" class="my_button" id="test" value="Test"/>
<input type="button" class="my_button" id="test2" value="Test-2"/>
Umair Hanif
  • 144
  • 1
  • 2
1

Try this:

<button class="my_button">Content1</button>
<button class="my_button">Content2</button>

<script>
$( ".my_button" ).click(function( event ) {
console.log(1);
});
</script>

https://jsfiddle.net/nt9ryeyr/5/

Frnnd Sgz
  • 236
  • 1
  • 4
  • 19
1

Try this:-

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".p").click(function(e){
        alert($(e.currentTarget).attr("value"));//button text on which you clicked
    });
});
</script>
</head>
<body>

<input type='button' class="p" value='test'/>

</body>
</html>
Sharique Ansari
  • 1,458
  • 1
  • 12
  • 22
1

if your html is like this

<button class="my_button">Test</button>
<button class="my_button">Test1</button>

then use this script

$('.my_button').click(function() {
if(this.innerHTML ==="Test")
    console.log(1);
else
console.log(2);
});

or if your html is like this

<input type="button" class="my_button" value="Test"/>
<input type="button" class="my_button" value="Test1"/>

then use this script

$('.my_button').click(function() {
if($(this).val() ==="Test")
    console.log(1);
else
console.log(2);
});
Optimus
  • 2,200
  • 8
  • 37
  • 71