Learning Horizon | For Learners

ASP.NET, SQL SERVER, JQUERY,JAVASCRIPT, WEBSPHERE

Thursday 11 April 2013

How To Get Specific Row ID In Dynamic Table Using Jquery

Today we will learn how to find/pick id of a row when tables are dynamic. I will explain it to you with the help of an example.

Example:-


I have generated a simple dynamic table with the help of for loop. Every row in a table has dynamic id e.g. Row0, Row1, Row3… and we need to find the id of the row when user clicks on any specific row. Normally you need id of the row when you want to perform some operation like edit/modify or delete.
I have used live () function here to pick row id of dynamic table. live () function simply attach an event with the selector. However in Jquery version 1.7 it is deprecated and in 1.9 it is removed. There are other function like delegate () and on () which you can use to attach event handlers.
This is the jquery code I have used to pick the id.

// ------------- Pick row id of the dynamic Table

        var tableRow = $("#tbl_Dynamic").find('tr');
        tableRow.live('click', function (e) {
            alert($(this).attr('id'));
        });
//-----------------end here--------------------------

Below mentioned is the full code example of simple dynamic table generation and pick the row id of a dynamic table.

<html>
<head>
<title>Getting Row Id of a Dynamic Table</title>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>

  <body>
       <div id="tableDiv" ></div>

</body>
    
    <script type="text/javascript" language="javascript">

// ------------- Pick row id of the dynamic Table

        var tableRow = $("#tbl_Dynamic").find('tr');
        tableRow.live('click', function (e) {
            alert($(this).attr('id'));
        });
//-----------------end here--------------------------
         
 $(document).ready(function () {
            dynamicTable();
 });

function dynamicTable(){
       
var table="";
var arrName = 
['Amir', 'Zeeshan', 'Kalim', 'Yasir', 'Zafar', 'Adeel', 'Majid', 'Pravin'];
var arrDept = 
['IT', 'HR', 'Finance', 'Marketing', 'Billing', 'IT', 'Web', 'Finance'];

table+="<table id='tbl_Dynamic' style='text-align:center;'>";
table+="<thead>";
table+="<tr><th>Serial #</th>";
table+="<th>Name</th>";
table+="<th>Department</th>";
              table+="</thead><tbody>";

              for (var i = 0; i < 8; i++) {

                  table += "<tr id='Row"+i+"'>";
                  table += "<td>" + i + " </td>";
                  table += "<td>" + arrName[i] + "</td>";
                  table += "<td >"+arrDept[i]+"</td>";
                  
                  table += "</tr>";

              }
                     table+="</tbody></table>";
                     $("#tableDiv").html(table);
}

</script>
</html>


jquery-example-one
jquery-example-one

No comments:

Post a Comment

Please do not enter spam links.