How to get selected row in Gridview in Javascript or JQuery
Let me get more details ... below is my partial gridview with a button field ... what I want is the text value of the button used when building the url:
<asp:GridView CssClass="gridUser" ID="UsersGrid" ClientIDMode="Static" runat="server" AllowPaging="true" AllowSorting="true" PageSize="5" OnPageIndexChanging="PageIndexChange" OnRowCommand="Paging" OnSorting="SortPage" OnRowCreated="RowCreated"
AutoGenerateColumns="false">
<PagerSettings Mode="NextPreviousFirstLast" FirstPageImageUrl="~/Images/Navigation/firstpageIcon.png" LastPageImageUrl="~/Images/Navigation/lastpageIcon.png"
NextPageImageUrl="~/Images/Navigation/forwardOneIcon.png" PreviousPageImageUrl="~/Images/Navigation/backOneIcon.png" Position="Bottom" />
<Columns>
<asp:TemplateField HeaderText="User Name" HeaderStyle-CssClass="gridHeader">
<ItemTemplate>
<asp:Button ID="UserLink" ClientIDMode="Static" runat="server" Text='<%#Eval("UserName") %>' CssClass="linkButton" OnClientClick = "return GetSelectedRow(this)"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
and here is my javascript:
$(".linkButton").click(function () {
var ul = document.getElementById('UserLink');
var row = ul.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var Userid = row.cells[0].childNodes[1].value;
var User = Userid;
alert("Row is : " + row + "RowIndex is : " + rowIndex + "User ID is " + User);
});
My problem is that my row returned is the first row ... not the selected row ... how do I get the selected row? Thanks for any help.
source to share
Try this ... Modify naming conventions as per your requirement
<script type = "text/javascript">
function GetSelectedRow(UserLink) {
var row = UserLink.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var Userid = row.cells[0].innerHTML;
alert("RowIndex: " + rowIndex + " Userid : " + Userid + ");
return false;
}
</script>
source to share
Your first problem is that in the button template column you are using Id=UserLink
that will repeat for every row. Item ID must be unique. For details see.
The second problem is that document.getElementById('UserLink');
it will actually find the first element with an ID UserLink
, which will always be the first row. In your case, you can var ul = this;
, and that should give you the button that was clicked.
Summarizing:
- I would like to suggest rolling the id on your button or making them unique.
- Change
document.getElementById('UserLink')
tothis
and this will trigger a button click.
source to share