1

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 ?

3 Answers 3

2
var arrValues = new Array();
function test() {
    $(":checkbox").each(function () {
        if (this.checked && arrValues.indexOf(this.value) == -1) {
            arrValues.push(this.value);
        }
    });
}
Sign up to request clarification or add additional context in comments.

5 Comments

where do i call this function test() ?
Other person says Whenever the user select an item So why iteration? and why not the click event ?
@Pankaj Garg I just base on his code to show how to add item to array
@PhongVo where do i call this function, inorder to add the checked items to arrya ?
@Anuya I just create a sample that will bind onclick event to checkbox to add value and remove it out of array jsFiddle
0

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..

1 Comment

Other person says Whenever the user select an item So why iteration? and why not the click event ?
0
var val;
$('#<%= chkServiceType_1.ClientID %> input[type=checkbox]').change(function(){
   val = $("#<%= chkServiceType_1.ClientID %> input[type=checkbox]:checked").map(function(){
          return this.value;
       }).get();
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.