Javascript onclick Event to get CheckBoxList Selected Value Selected Index Selected Text ASP.Net C# VB.Net

To read CheckBoxList Selected Value, Selected Index & Selected Text in server side is an easy job but using javascript its a bit difficult. In this article i want to share with you how one can read CheckBoxList SelectedValue, SelectedIndex & SelectedText by using javascript onclick event. Before explanation i want to share with you that getting SelectedIndex & SelectedText from javascript is a bit easy rather than SelectedValue because there is no direct way to read SelectedValue from CheckBoxList. To do that you have to work a bit hard, like during databound time of CheckBoxList you have to add an additional attribute named ALT as value. Then from checkbox array you can read the ALT value as SelectedValue. I did not found any other easy alternatives yet. If you do not want to read Selected Value of CheckBoxList then please remove the CheckBoxList1_DataBound method from server side code as well as remove variables spanArray, sValue & its related lines from javascript method.

Focus Area:
1. How to get SelectedValue from Asp.Net CheckBoxList using javascript onclick event.
2. How to get SelectedText from Asp.Net CheckBoxList using javascript onclick event.
3. How to get SelectedIndex from Asp.Net CheckBoxList using javascript onclick event.

To complete the all examples create a sample table like below:

CREATE TABLE [dbo].[Article](
    [ArticleID] [int] NOT NULL,
    [Title] [varchar](max) NOT NULL,
    [IsPublished] [bit] NOT NULL,
([ArticleID] ASC)

Insert Some Sample Data:

INSERT INTO ARTICLE VALUES(1,'Populate SQL Data Into Checkboxlist',1)
INSERT INTO ARTICLE VALUES(2,'Checkboxlist data population example',0)
INSERT INTO ARTICLE VALUES(3,'C# Checkboxlist lesson',1)
INSERT INTO ARTICLE VALUES(4,'VB.Net Checkboxlist Example',0)
INSERT INTO ARTICLE VALUES(5,' Checkboxlist load data',0)

Modify the web.config file to connect to your Database like below:

    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Test;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now prepare the HTML Markup like below:

<asp:CheckBoxList ID="CheckBoxList1" runat="server" onclick="Get_Selected_Value();" OnDataBound="CheckBoxList1_DataBound">
<hr />
<label id="lbl_SelectedValue" runat="server"></label><br />
<label id="lbl_SelectedText" runat="server"></label><br />
<label id="lbl_SelectedIndex" runat="server"></label>

Now prepare the Javascript Function like below:

<script type="text/javascript">
    function Get_Selected_Value() {
        var ControlRef = document.getElementById('<%= CheckBoxList1.ClientID %>');
        var CheckBoxListArray = ControlRef.getElementsByTagName('input');
        var spanArray = ControlRef.getElementsByTagName('span');
        var checkedValues = '';
        var nIndex = 0;
        var sValue = '';

        for (var i = 0; i < CheckBoxListArray.length; i++) {
            var checkBoxRef = CheckBoxListArray[i];

            if (checkBoxRef.checked == true) {
                var labelArray = checkBoxRef.parentNode.getElementsByTagName('label');

                if (labelArray.length > 0) {
                    if (checkedValues.length > 0) {
                        checkedValues += ', ';
                        nIndex += ', ';
                        sValue += ', ';
                    checkedValues += labelArray[0].innerHTML;
                    nIndex += i;
                    sValue += spanArray[i].alt;
        document.getElementById('<%= lbl_SelectedValue.ClientID %>').innerHTML = '<b>Selected Value:</b> ' + sValue;
        document.getElementById('<%= lbl_SelectedText.ClientID %>').innerHTML = '<b>Selected Text:</b> ' + checkedValues;
        document.getElementById('<%= lbl_SelectedIndex.ClientID %>').innerHTML = '<b>Selected Index:</b> ' + nIndex;

Now first bind the CheckBoxList from Database under Page_Load Event:
C# Code:

        if (!IsPostBack)
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
                SqlDataAdapter ad = new SqlDataAdapter("SELECT ArticleID,Title from Article", conn);
            CheckBoxList1.DataSource = dt;
            CheckBoxList1.DataTextField = "Title";
            CheckBoxList1.DataValueField = "ArticleID";

Note: Don’t forget to add “using System.Data.SqlClient;”, “using System.Configuration;”, “using System.Data;” namespaces.

VB.Net Code:

        If Not IsPostBack Then
            Dim dt As DataTable = New DataTable()
            Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString)
                Dim ad As SqlDataAdapter = New SqlDataAdapter("SELECT ArticleID,Title from Article", conn)
            End Using

            CheckBoxList1.DataSource = dt
            CheckBoxList1.DataTextField = "Title"
            CheckBoxList1.DataValueField = "ArticleID"
        End If

Note: Don’t forget to add “Imports System.Data.SqlClient”, “Imports System.Configuration”, “Imports System.Data” namespaces.

To Get SelectedValue we need to do some more work. Write the below server side code under CheckBoxLixt DataBound Event. If you don’t need to read CheckBoxLixt currently selected item SelectedValue then you can omit this part.

C# Code:

    protected void CheckBoxList1_DataBound(object sender, EventArgs e)
        CheckBoxList chkList = (CheckBoxList)(sender);
        foreach (ListItem item in chkList.Items)
            item.Attributes.Add("alt", item.Value);

VB.Net Code:

    Protected Sub CheckBoxList1_DataBound(sender As Object, e As EventArgs)
        Dim chkList As CheckBoxList = CType(sender, CheckBoxList)
        For Each item As ListItem In chkList.Items
            item.Attributes.Add("alt", item.Value)
    End Sub

Now run the project. Hope you can get or read CheckBoxList Selected Item – Selected Value, Selected Index & Selected Text from Javascript onclick event.


Download Code Example C#        Download Code Example VB.Net

Posted in .Net,, C#, Client, Javascript, VB.Net
One comment on “Javascript onclick Event to get CheckBoxList Selected Value Selected Index Selected Text ASP.Net C# VB.Net
  1. sohrab says:

    hi sir.thanks for your best reg

Leave a Reply

Your email address will not be published. Required fields are marked *