Know which button was clicked

Asked

Viewed 1,860 times

4

Friends, I have 4 buttons like <input tupe="button">, each 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, because the id is unique, the class is different. Thank you.

1 answer

6

With jQuery you can just do it:

$('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 so:

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 classes shared. In your text you say "each has a different class [...] the id is unique", maybe it’s right but the description gives me idea that not

Browser other questions tagged

You are not signed in. Login or sign up in order to post.