I want to get Id
of row clicked when a user clicks a button.
My code is as below.
<table cellpadding="0" cellspacing="0" id="ProductGrid">
<tr>
<th>P Id</th>
<th>P Name</th>
<th>Price</th>
<th></th>
</tr>
@foreach(Mvc4API.linqtosql.tblProduct prod in Model)
{
<tr>
<td>@prod.Pid</td>
<td>@prod.Pname</td>
<td>@prod.Price</td>
<td><button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview()"></button></td>
</tr>
}
</table>
I tried:-
function getview() {
debugger;
var productId = $("#ProductGrid .ids").closest("tr").find("td").eq(0).html();
});
But it is not working.
Duplicate id attributes are invalid html. Remove the id
attribute and the onclick
and use
$('.ids').click(function() {
var productId = $(this).closest("tr").find("td").eq(0).text();
});
Alternatively, add the value in a data
attribute
<button type="button" class="ids" data-id="@prod.Pid"></button>
and use
$('.ids').click(function() {
var productId = $(this).data('id');
});
Note that your current selector - $("#ProductGrid .ids")
returns all the button elements, not the one you clicked.
Just update the tag.
button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview()"
to
button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview(this)"
It will give you the id in script.
Change the button tag like this
<td><button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview(@prod.Pid)"></button></td>
and the JS function like this
function getview(id) {
debugger;
var productId = id;
});
Try following code.
View
<td><button type="button" class="ids" id="btnpartial" value="showdetail" onclick="getview(@prod.Pid)"></button></td>
Script
function getview(x)
{
var id = x; //Id will get here.
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.