skip to Main Content

I have created a bootstrap datatable with just header names. The row values in the table are going to come dynamically when I fill a form. Now when I click on any row of the table it should redirect me to a different page based on the id value of the row. now in my case if ID = 3 and Name = Roger it should redirect me to a page which displays ID as 3 and Name as Roger.

       <table id="test">
        <thead>
            <tr>
                <th>
                    Name
                </th>
                <th>
                    Age
                </th>
                <th>
                    Game
                </th>
                <th>
                    ID
                </th>
            </tr>
        </thead>
    </table>

I am a newbie in Jquery. Can anyone help me with the jquery code? I have created a query like this.

$(document).ready(function () {
$("tr").not(':first').click(function () {
    let name = $(this).find("td:first").text();
    let age = $(this).find("td:eq(1)").text();
    let game = $(this).find("td:eq(2)").text();
    let id = $(this).find("td:eq(3)").text();
    let newUrl = "/Details/Index/view?id=" + id + "&name=" + name;
    location.href = newUrl;
 });
});

Here Details is my Controller name and Index is my view name. It is not redirecting to the page.
Thanks in advance.

2

Answers


  1. You could do it like this:

     $(document).ready(function() {
        $("tr").not(':first').click(function(){
           let id = $(this).find("td:first").text();
           let name = $(this).find("td:eq(1)").text();
           let newUrl = "http://example.com/view?id=" + id + "&name="  + name;
           location.href= newUrl;
        });
     });
    
    Login or Signup to reply.
  2. use onclick attribute on <td>

    <table style="width:100%">
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Age</th>
        <th>Game</th>
      </tr>
      <tr onclick="document.location='www.url.com/01'" >
        <td>01</td>
        <td>Walter White</td>
        <td>50</td>
        <td>E.T. the Extra-Terrestrial</td>
      </tr>
      <tr onclick="document.location='www.url.com/02'" >>   
        <td>02</td>
        <td>Jesse Pinkman</td>
        <td>23</td>
        <td>Friday the 13th</td>
      </tr>
    </table>
    

    Use js to dynamically add the custom URL for each row.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search