encodedna - jquery

Check if Any GridView Row With RadioButton is Selected Using JQuery.

February 08th, 2013
jquery gridview asp.net
We have used the GridView control in Asp.Net for various purposes in our projects, time and again for a long very time now. But we know that most of its features are available at the server side. Using JQuery we can do some useful validations at the client side on the GridView control.

JQuery, as we know is a JavaScript library which simplifies validations and manipulations of various controls, pages etc. at the client side.

This article will demonstrate how to “Check” if any GridView row with “RadioButton” has been selected (Checked) using “JQuery”. RadioButton on a GridView will allow the user to select one row at a time. The validation will be done on the “Click” of a button control.

$('#btView').click(function() {
        var bSelected = true;
        var sEmpName;
        $('#gvDime').find('input:radio').each( …
});             

GridView Row Validation usgin JQuery

Note: We will also see how only a “Single” radio button will be selected using a function written in JQuery.

Start “Visual Studio” and from the “File” menu open “New Web Site” and select “Asp.Net Web Site” and click OK.

Add a “GridView” control along with an “SqlDataSource” control from the toolbox. We will bind the GridView with a database table using SqlDataSource to show few rows.

If you have not done this yet, then we recommend you check the below read on How to bind a GridView with SqlDataSource Control!

Once GridView control has been binded with the database, add a “Column” with a “RadioButton” at beginning of the GridView.

<Columns>
    <%--ADD THIS COLUMN AFTER BINDING THE GRID WITH SQLDATASOURCE--%>
    <asp:TemplateField>
        <ItemTemplate>
            <asp:RadioButton runat="server" id="rbEmp" OnClick="javascript:check(this.id)" />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>    
Complete Source (Default.aspx)
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Validate GridView using JQuery</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div style="font:12px/0.8 tahoma,Arial">
            <%--THE GRIDVIEW CONTROL.--%>
            <asp:GridView ID="gvDime" runat="server" AutoGenerateColumns="False"
                DataSourceID="SqlDataSource1">
                <Columns>
                    <%--ADD THIS COLUMN AFTER BINDING THE GRID WITH SQLDATASOURCE--%>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:RadioButton runat="server" id="rbEmp" OnClick="javascript:check(this.id)" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    
                    <asp:BoundField DataField="EmpID" HeaderText="EmpID" SortExpression="EmpID" />
                    <asp:BoundField DataField="EmpName" HeaderText="EmpName"
                        SortExpression="EmpName" />
                    <asp:BoundField DataField="Country" HeaderText="Country" 
                        SortExpression="Country" />
                    <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
                </Columns>
                <HeaderStyle BackColor="BurlyWood" BorderColor="Gray" Font-Bold="True" 
                    ForeColor="White" Height="20px" />
                <RowStyle BackColor="Wheat" BorderColor="GrayText" ForeColor="#000" 
                    HorizontalAlign="Center" Height="20px" />
            </asp:GridView>
            
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:DNA_CLASSIFIEDConnectionString %>" 
                SelectCommand="SELECT [EmpID], [EmpName], [Country], [Email] FROM [EmployeeDetails]">
                </asp:SqlDataSource>
        </div><br />
        <input type="button" id="btView" value="View Details" />
    </form>
</body>
<script type="text/javascript">
    // SELECT SINGLE RADIO BUTTON ONLY.
    function check(objID) {
        var rbSelEmp = $(document.getElementById(objID));
        $(rbSelEmp).attr('checked', true);  // CHECK RADIO BUTTON WHICH IS SELECTED.

        // UNCHECK ALL OTHER RADIO BUTTONS IN THE GRID.
        var rbUnSelect = rbSelEmp.closest('table').find("input[type='radio']").not(rbSelEmp);
        rbUnSelect.attr('checked', false);
    }

    $('#btView').click(function() {
        var bSelected = true;
        var sEmpName;
        $('#gvDime').find('input:radio').each(function() {  // CHECK EACH ROW FOR THE SELECTED RADIO BUTTON.
            var name = $(this).attr('name');
            if ($('input:radio[name=' + name + ']:checked').length == 0) { bSelected = false }
            else {
                // GET THE EMPLOYEE NAME (3rd COLUMN) FROM THE ROW WHICH IS CHECKED.
                sEmpName = $('input:radio[name=' + name + ']:checked').closest('tr').children('td:nth-child(3)').map(function() {
                    return $.trim($(this).text());
                }).get();
            }
        });
        if (bSelected == false) { alert('Invalid Selection.'); return false }
        else alert('Employee Name: ' + sEmpName);
    });
</script>
</html>

For any queries, please send us an Email.

jquery gridview asp.net