Display Selected ASP.NET Checkbox Label using jQuery

ASP.NET Checkbox server control's text get render as label, using jQuery we can find our labels for only those Checkboxes that are selected. You can use it for many different purposes and one of that we will look at in future article.

ASPX and jQuery Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CheckboxListWithArray.aspx.cs" Inherits="CheckboxListWithArray" %>

 

<!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></title>

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:CheckBoxList ID="CheckBoxList1" runat="server">

<asp:ListItem>1</asp:ListItem>

<asp:ListItem>2</asp:ListItem>

<asp:ListItem>3</asp:ListItem>

<asp:ListItem>4</asp:ListItem>

<asp:ListItem>5</asp:ListItem>

</asp:CheckBoxList>

<input id="Button1" type="button" value="Go" onclick="checkSelection();"/>

<p id="result"></p>

</div>

 

<script type="text/javascript">

function checkSelection() {

// getting all checkboxes on tha page under checkboxlist1

var checkboxes = $('#CheckBoxList1 input[type=checkbox]');

// creating a new array object to hold selected results

var chkArray = new Array();

var j = 0;

// iterating over all checkboxes and checking if its selected

$.each(checkboxes, function (index, value) {

if ($('#' + value.id).is(':checked')) {

chkArray[j] = "'" + $('#' + value.id).next().text() + "'";

j++;

}

});

// joining result using array's join method

$('#result').text(chkArray.join(', '));

}

</script>

</form>

</body>

</html>

 

Tags: , , , , , ,

ASP.NET | jQuery