Updating textbox with checked items using jQuery
I have a CheckBoxList. When the user checks or unchecks the items in the CheckBoxList, a TextBox should be updated with the checked values separated by a comma. How can I do this?
You can open up the designer. Add a CheckBoxList and TextBox as shown below:
<asp:CheckBoxList ID="CheckBoxList1" runat="server"> <asp:ListItem>House</asp:ListItem> <asp:ListItem>Car</asp:ListItem> <asp:ListItem>Bike</asp:ListItem> </asp:CheckBoxList> Choice: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
After adding the HTML, you can add a simple script using jQuery. The script will set up the click() handler of the checkbox to update the textbox as shown below:
$(document).ready(
function init() {
$.each($('input[name*=CheckBoxList1]'),
function () {
$(this).click(
function () {
var txt = '';
$.each($('input[name*=CheckBoxList1]:checked'),
function () {
txt = txt + $(this).val() + ',';
});
if (txt.length > 0)
txt = txt.substring(0, txt.length - 1);
$('input[name$=TextBox1]').val(txt);
});
});
}
);
The selector for Checkboxes uses the [name*=CheckBoxList1]. This gets all input elements which has CheckBoxList1 embeeded within the name.
Posted by Vijay on 19-Apr-2011 10:28 AM
Category : Javascript
Category : Javascript
Please leave your comment
Hi, thank you so much for your valuable code... Colud I except the code in the asp.net... I would greatly appreciate you..
Thank you..