Anuya
Anuya

Reputation: 8350

How to save the selected value of checkboxlist in array?

I want to save the values of checkbox in an array using javascript or jquery. My checkboxlist is inside the datalist. Whenever the user select an item, I want to add the value of that selected item to a array.

ASPX :

 <asp:DataList ID="dl_Groups_1" RepeatColumns="1"  runat="server" OnItemDataBound="dl_Groups_1_ItemDataBound" RepeatDirection="vertical" ShowFooter="False" ShowHeader="False">
        <ItemTemplate>
           <asp:CheckBox Font-Bold="true" runat="server" ID="chk_Group_1" Text='<%# Eval("category_type") %>' Value='<%# Eval("service_type_category_id") %>' onclick="OnGroupClick" />
            <asp:CheckBoxList  CssClass="line" runat="server" ID="chkServiceType_1" DataValueField="ServiceTypeID" DataTextField="Name" EnableViewState="true">
            </asp:CheckBoxList> 
            <br />
        </ItemTemplate>
    </asp:DataList>

I tried the below to, get the items that are slected, but i am struck up here...

function test() {
    $(":checkbox").each(function () {
        if (this.checked) {
            alert(this);
        }
    });
}

When i do this, i get alert message as "ON" and not the value. And where do i call the javascript to keep the array updated on selecting and un selecting the items in checkboxlist ?

Upvotes: 1

Views: 1660

Answers (3)

Anujith
Anujith

Reputation: 9370

var val;
$('#<%= chkServiceType_1.ClientID %> input[type=checkbox]').change(function(){
   val = $("#<%= chkServiceType_1.ClientID %> input[type=checkbox]:checked").map(function(){
          return this.value;
       }).get();
})

Upvotes: 0

bipen
bipen

Reputation: 36531

use map()

 var selectedValue= $("input:checkbox:checked").map(function(){
     return this.value;
 }).get();

console.log(selectedValue);

selectedValue will have all the checked value in array..

Upvotes: 0

Phong Vo
Phong Vo

Reputation: 1078

var arrValues = new Array();
function test() {
    $(":checkbox").each(function () {
        if (this.checked && arrValues.indexOf(this.value) == -1) {
            arrValues.push(this.value);
        }
    });
}

Upvotes: 2

Related Questions