Know which button was clicked

4

Friends, I have 4 buttons type <input tupe="button"> , each one has a different class because they are formatted in different ways. Both buttons have the same action, with different values only. I would like to know how to get these values from these buttons in a jquery function, since the id is unique, the class is different. Thank you.

    
asked by anonymous 18.12.2015 / 12:53

1 answer

6

With jQuery you can simply do:

$('button[type="button"]').on('click', function(){
   // e aqui, o this é o botão clicado
   var id = this.id;
   var classes = this.classList;
});

If you want to do only with native JavaScript you can do this:

var botoes = document.querySelectorAll('button[type="button"]');
for (var i = 0; i < botoes.length; i++){
  botoes[i].addEventListener('click', function(){
       // e aqui, o this é o botão clicado
       var id = this.id;
       var classes = this.classList;
  });
}

Note:

  • Notice that you have tupe instead of type .
  • Remember that IDs must be unique, and shared classes. In your text you say "each one has a different class ... the id is unique", maybe it's right but the description gives me an idea that it is not
18.12.2015 / 12:57