Check if Any GridView Row With RadioButton is Selected Using JQuery

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

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

This article will demonstrate how you can use “JQuery” to validate and check if any GridView row with “RadioButton” has been selected (Checked). RadioButton on a GridView will allow the user to select one row at a time. We will add a “button” control in our project and its “Click” event will execute the validation process.

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

GridView Row Validation usgin JQuery

Note: Also in this article, we will see how to restrict “single” radio button selection using a function written in JQuery.

Start “Visual Studio” and using the “File” menu open “New Web Site” and select “Asp.Net Web Site”. Choose the language you are comfortable to execute this demo. This article has code written in C# and Vb.Net.

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

We have previously written an article on How to bind GridView with SqlDataSource Control. We recommend that you first read the article to have a better understanding of data binding.

Once you have bound the GridView control 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>
The Markup with the GridView Control
<!DOCTYPE html>
<html>
<head>
    <title>Validate GridView using JQuery</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <%--STYLE THE GRIDVIEW--%>
    <style type="text/css">
    
        div { font:11px Verdana; width:500px }
        
        .grid { width:100%; font:inherit; background-color:#FFF; border:solid 1px #525252 }
        .grid td { font:inherit; padding:2px; border:solid 1px #C1C1C1; color:#333; 
            text-align:center; text-transform: uppercase
        }
        .grid th { padding:3px; color:#FFF; background:#424242 url(grd.png) repeat-x top; 
            border-left:solid 1px #525252; font:inherit; text-align:center; text-transform:uppercase
        }
        input { width:auto; background-color:#4F94CD; color:#FFF; padding:3px;
            border:solid 1px #4F94CD; border-radius:3px; -moz-border-radius:3px; 
            -webkit-border-radius:3px; cursor:pointer;
        }
    </style>
</head>
<body>
        <div>
        
            <%--THE GRIDVIEW CONTROL.--%>
            <asp:GridView> ID="gvDime" runat="server" CssClass="grid" GridLines="None" 
                AutoGenerateColumns="False"DataSourceID="SqlDataSource1">
                
                <Columns>
                    <%--ADD "CHECKBOX" COLUMN AFTER BINDING THE GRID WITH SQLDATASOURCE--%>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:RadioButton runat="server" id="rbEmp" OnClick="javascript:check(this.id)" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    
                    <%--FIELDS OF DATABASE TABLE WHICH WAS BOUND USING "SQLDATASOURCE"--%>
                    <asp:BoundField DataField="EmpID" HeaderText="Emp. ID" SortExpression="EmpID" />
                    <asp:BoundField DataField="EmpName" HeaderText="Employee Name" SortExpression="EmpName" />
                    <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
                    <asp:BoundField DataField="Email" HeaderText="Email Address" SortExpression="Email" />
                </Columns>
                
            </asp:GridView>
            
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:DNA_CLASSIFIEDConnectionString %>" 
                
                SelectCommand="SELECT [EmpID], [EmpName], [Country], [Email] FROM [EmployeeDetails]">
            </asp:SqlDataSource>
            
        </div>
        
        <p><input type="button" id="btView" value="View Details" /></p>
</body>
JQuery script for validation
<script>
    // 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;
        
        // CHECK EACH ROW FOR THE SELECTED RADIO BUTTON.
        $('#gvDime').find('input:radio').each(function() {  
            
            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();
            }
        });
        
        // FINALLY SHOW THE MESSAGE.
        if (bSelected == false) { 
            alert('Invalid Selection'); return false 
        }
        else 
            alert('Employee Name: ' + sEmpName);
    });
</script>
</html>
comments powered by Disqus

Join our Google Plus Community and be a part of a discussion!