-4

I'm binding a click event to buttons created dynamically in a table of class .lada-button.

In the current setup creating a reference to the button using a class selector Ladda.create( document.querySelector( '.ladda-button' ) ); triggers the submit transition only for the first button in the table. Instead of the button that has been clicked.

So in order to trigger it for the button that had been clicked, I tried getting the id of the clicked button which returns undefined for the id attribute:

<tbody>
    @foreach (var row in Model.Status)
    {
         <tr>
             <td style="visibility:hidden;" >@Html.Raw(row.ID)</td>            
             <td><button type="submit" data-style="expand-right" class="ladda-button"><span class="ladda-label">Update</span><span class="ladda-spinner"></span></button></td>
         </tr>
    }
</tbody>
$(".ladda-button").click(function () {
    var btnId = $(this).attr('id');
    alert(btnId);
    var updateBtn = Ladda.create( document.querySelector( btnId ) );
    // Start loading
    updateBtn.start();
});

How can you get the id attribute of clicked tr button element?

Robin Daugherty
  • 7,115
  • 4
  • 45
  • 59
Brian Var
  • 6,029
  • 25
  • 114
  • 212
  • How is your HTML layout? Maybe you need get the parent `$(this).parent().attr('id')` – laurent Oct 03 '16 at 10:35
  • You don't need jquery... just use `this.id` or the parent element's ID `this.parentElement.id` – evolutionxbox Oct 03 '16 at 10:36
  • 3
    well, maybe I'm wrong but it seems it's undefined because you don't have any id attribute on your button: – Gatsbill Oct 03 '16 at 10:36
  • @Gatsbill the table rows containing the buttons are created dynamically so I haven't set an id attribute for them. – Brian Var Oct 03 '16 at 10:37
  • 2
    So what you want to get ??? – Zakaria Acharki Oct 03 '16 at 10:38
  • I want to try to get a reference to the clicked button element, in order to create the `Ladda` object which references the clicked button. For example... `var updateBtn = Ladda.create( document.querySelector( this.id ) );` – Brian Var Oct 03 '16 at 10:40
  • 2
    I think the problem is in the `document.querySelector( btnId )` part. You have to prepend the id with "#" to indicate the selector is an id and not an element. – Erik Svedin Oct 03 '16 at 10:41
  • Ok I did try that like so.. `var updateBtn = Ladda.create( document.querySelector( '#' + this.id ) );` but got an `Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': '#' is not a valid selector` – Brian Var Oct 03 '16 at 10:43
  • well you have to make sure that you get the correct id as well, it cant be undefined or null. See answers how to grab closest tr reference – Erik Svedin Oct 03 '16 at 10:44

1 Answers1

-1

You can use jquery closest function.

You can see a simple example here

$("button").click(function(event) {
    alert($(this).closest("tr").attr("id"));
});

https://jsfiddle.net/0pxswgt6/2/

Luis M. Villa
  • 159
  • 11