Click action with jquery does not work with duplicate items

Asked

Viewed 436 times

0

I have two buttons on my page that serve to delete users, one I put at the top of the table where displays users along with paging and the other at the bottom, also along with paging. I put so to facilitate user navigation, but my jquery function that is triggered by the event click of this button, only works with the button at the top, if I put the buttons with different ids and two separate functions for each they work, but wanted a method that fit both.

//A função está mais ou menos assim
$("#deletar").click(function(){
    //Faz algo aqui
}

I tested a few jquery selectors, but was unsuccessful.

2 answers

2


Ids must be unique. That means you can only have 1 per page.
In these cases you should use classes to group elements with the same identifier.

Mute:

  • #deletar for .deletar on the jQuery selector
  • id="deletar" for class="deletar" in HTML.

1

You cannot assign the same id to more than one element on the page. If you do this, DOM will always get the first id page and ignore other page(s) (s).

So assign a id for each element you want to click and add a class equal for them:

<input class="botoes" type="button" value="Botão 1" id="botao1" />
<br /><br />
<input class="botoes" type="button" value="Botão 2" id="botao2" />

This way, when the element is clicked, you can get the information you need with jQuery from the class:

$('.botoes').on('click', function(){
    alert('Botão com "id='+this.id+'" clicado!');
});

$('.botoes').on('click', function(){
	alert('Botão com "id='+this.id+'" clicado!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="botoes" type="button" value="Botão 1" id="botao1" />
<br /><br />
<input class="botoes" type="button" value="Botão 2" id="botao2" />

Browser other questions tagged

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