Rieth
Rieth

Reputation: 295

Dynamic jquery selector based on html attribute

I have the following code:

<table id="Product">
       <thead>
              <tr>
                    <th>ProductId</th>
                    <th>Productname</th>
                    <th>Quantity</th>
                    <th>UnitPrice</th>
              </tr>
       </thead>
       <tbody>

       </tbody>
</table>

<button id="add" data-table="Product" data-url="Product/Add"></button>

Then in javascript file:

     $('#add').click(function () {
            var url = $(this).attr("data-url");
            var table = $(this).attr("data-table");
            var tableBody = ???; 
            //some logic with tablebody

    });

How can i get table body of the table?

Upvotes: 0

Views: 64

Answers (2)

ericbn
ericbn

Reputation: 10948

$('#add').click(function () {
    var $this = $(this);
    var url = $this.data("url");
    var tableId = $this.data("table");
    var $tableBody = $("#" + tableId + " tbody");
});

Read more about jQuery selectors at https://api.jquery.com/category/selectors/

Here I'm using the ID Selector and the Descendant Selector.

Upvotes: 2

Juan Pablo Baltra
Juan Pablo Baltra

Reputation: 23

 $('#add').click(function () {
        var url = $(this).attr("data-url");
        var table = $(this).attr("data-table");
        var tableBody = $("#" + table).find("tbody"); 
        //some logic with tablebody

});

Upvotes: 1

Related Questions