Jquery click action does not work with duplicate items

0

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

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

I tested some jquery selectors, but I did not succeed.

    
asked by anonymous 12.10.2017 / 21:07

2 answers

3

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

Changes:

  • #deletar to .deletar in the jQuery selector
  • id="deletar" to class="deletar" in HTML.
12.10.2017 / 21:13
1

You can not assign the same id to more than one element on the page . If you do this, the DOM will always pick up the first% of the page and ignore the other

So, assign a id to each element you want to click and add a id equal to 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" />

In 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><inputclass="botoes" type="button" value="Botão 1" id="botao1" />
<br /><br />
<input class="botoes" type="button" value="Botão 2" id="botao2" />
    
12.10.2017 / 21:40