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

Asked

Viewed 43 times

3

I’m doing a user-friendly Dashboard and I need a button to edit. When the edit button runs it just makes code appear and disappear, but wanted to know if it is possible to execute jQuery code and select the id of the button.

inserir a descrição da imagem aqui

<a id="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);
});
  • This html is badly formatted <a id="1"edit"> ... the edit is a class?

  • 1

    @Sergio sorry yes is a class="Edit" and in jquery missing the '.Edit'

3 answers

2


Your html <a id="1"edit">E</a> is poorly formatted, but assuming your selector works, inside 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);
});
  • 1

    It worked, thank you. D

0

You’ll have to add a class to your own anchor 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: There it is 'body' for event delegation because it smells to me like you’re adding elements dynamically. If that’s true, you can:

  • a) Grab the event on-click while doing the .append() of html
  • b) Make Event delegation, which is like saying: "hook an event that is always in html while target is dynamic"

0

The ID attribute as well as classes should not be started by numbers, and since you apparently need the ID number to select the record in the BD, I recommend using the attribute data-id thus:

$('.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>
<a data-id="1" class="edit">E</a>
<a data-id="2" class="edit">E</a>
<a data-id="3" class="edit">E</a>

Browser other questions tagged

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