当前位置: 动力学知识库 > 问答 > 编程问答 >

Extract a Cell/Td/tabledata value from a given row of a table using javascript/jquery

问题描述:

Here is my html table that is used in the Asp.net MVC razor view

<table class="table-striped table-bordered">

<thead>

<tr>

<th class="col-md-2">

Id

</th>

<th class="col-md-4">

Description

</th>

<th class="col-md-3">

Quantity

</th>

<th class="col-md-3">

AssetType

</th>

</tr>

</thead>

<tbody>

@foreach (var i in Model)

{

<tr>

<td class="col-md-2">

@i.Id

</td>

<td class="col-md-4">

@i.Description

</td>

<td class="col-md-3">

@i.Count

</td>

<td class="col-md-3">

@i.AssetType

</td>

<td>

<a onclick="getId()">Edit</a>

</td>

</tr>

}

</tbody>

</table>

My Js Code

<script type="text/javascript">

var getId = function () {

//get current row

var currentRow = $(this).closest('tr');

// get the id from the current row. or is there any better way ?

}

</script>

Hi In the above code. all i want to do is when the user selects the edit link of the given row in the table. i want to extract id value of the selected row.

Could anyone please guide me in this one? I have seen articles that says how to get a given cell value from each row but didnt have any luck in finding articles that explains how to extract the data cell value from a given row.

网友答案:

You already have it since you are generating the HTML from server side, when the user clicks pass the id to the funcion to do whatever you want with it.

 <td>
    <a onclick="getId('@i.Id')">Edit</a>
 </td>

function getId(id) {...}

or if you prefer you can use something like this:

 <a onclick="getId(this)">Edit</a>
        function getId(dom){
          var id = $(dom).parent().find('.col-md-2').html();
         }
网友答案:

You can put the id value to data-id attribute in the Edit link as below

<a data-id="@i.Id" class="edit-button" href="#">Edit</a>

Add the click event handler to the edit link, you can get the id value by using $(this).data('id')

<script type="text/javascript">
    $('.edit-button').on('click', function (e) {
        e.preventDefault();
        alert($(this).data('id'));
    });
</script>

Working fiddle: http://jsfiddle.net/ds4t6jur/

分享给朋友:
您可能感兴趣的文章:
随机阅读: