Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am have the below checkboxes and I want to pass the checked values to an array so that I can do an ajax post. However, I am hitting an error and I am not sure where I went wrong... How do I pass the values into the array and how do I retrieve them?

HTML

<input type="checkbox"  name="newCheckboxes" value="1"  />
<input type="checkbox"  name="newCheckboxes" value="2"  />
<input type="checkbox"  name="newCheckboxes" value="3"  />

Script (not working)

 var allFields = $( [] );
 $("#newCheckboxes:checked").each(function() {
         allFields.add( $(this).val() );
 });

 $.ajax(
      {
        type:"POST",
        url: "PostedHere",
        data:{
             checkedValues: allFields

              }
         });
share|improve this question

3 Answers

You only need:

$.ajax({
    type:"POST",
    url: "PostedHere",
    data: { checkedValues: $("#newCheckboxes:checked").serialize() } 
});
// checkedValues: "newCheckboxes=1&newCheckboxes=2" etc..
share|improve this answer
Thank you for your help. I cant seem to retrieve it at my servlet "PostedHere". I used String checkedValues= (String) request.getParameter("checkedValues"); Is this the right way? – newtodatatables Aug 4 '11 at 7:42

Using karim79 code idea:

$.post('URL', $('[name="newCheckboxes"]:checked').serializeArray(), function(data){
  //data
});
share|improve this answer
any idea how i can extract out the info at my URL? – newtodatatables Aug 4 '11 at 7:43

What I prefer to do is: Create a new Object and add all checkboxes 'Value' and 'Ischecked' to an array (access), then pass it to page by Json:

 $(document).ready(function () {
                    $("#btnSave").click(function () {
                         event.preventDefault();
                         $("#newCheckboxes").each(function () {
                         var data= new Object()
                         var access = new Array();
                         access.ChValue = $(this).attr("value");
                    if ($(this).attr("checked") == "checked") access.ChChecked = true;
                    data.push(access);
                });

 $.ajax({
                type: 'POST',
                url: '@Url.Content("~/URLofPage")',
                data: $.json.encode(data),
                dataType: 'json',
                contentType: 'application/json; charset=utf-8'

            });
});
});

please do not forgot to add Json reference to your page:

<script src="../../../Scripts/jquery.json.js" type="text/javascript"></script>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.