how to execute a specific button in a list of 5 identical buttons

3

I'm doing a dashboard with users and need an edit button. When the edit button runs it just makes code appear and disappear, but wanted to know if it's possible to execute jQuery code and select the button id.

<aid="1" class="edit">E</a>
<a id="2" class="edit">E</a>
<a id="3" class="edit">E</a>

$('.edit').on('click',function(){
    var id = $('.edit').id;
    alert(id);
});
    
asked by anonymous 07.10.2016 / 12:34

3 answers

2

Your html <a id="1"edit">E</a> is badly formatted, but based on the principle that your selector works, within the jQuery callback you can use this.id to know the ID of the element that originated the event.

$('a.edit').on('click',function(){
    var id = this.id;
    alert(id);
});
    
07.10.2016 / 12:42
0

You will have to add a class to your a nchor tags, like this:

<div class="wrapper">
    <a id="1" class="edit">E</a>
    <a id="2" class="edit">E</a>
    <a id="2" class="edit">E</a>
</div>

$('.edit').on('click', 'body', function (evt) {
    var thisElement = $(this); // isto é o A que foi clicado
    var id = thisElement.attr('id'); // .attr() retira o atributo que lhe passas
});

ps: It's there 'body' to event delegation because it smells like you're adding elements dynamically. If this is true, you can:

  • a) Grab the on-click event while you are doing .append() html
  • b) Make an event delegation, which is like saying: "hook to an event that is always in html while the target is dynamic"
07.10.2016 / 12:43
0

The ID attribute as well as classes should not be started by numbers, and as you apparently need the ID number to select the record in the DB, I recommend that you use the data-id attribute like this:

$('.edit').on('click',function(){
    alert($(this).data('id'));
});
.edit {
  display: inline-block;
  padding: 10px 20px;
  margin: 10px;
  border: 1px solid gray;
  background: PaleGreen;
  border-radius: 5px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><adata-id="1" class="edit">E</a>
<a data-id="2" class="edit">E</a>
<a data-id="3" class="edit">E</a>
    
07.10.2016 / 14:46