2

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

              }
         });

3 Answers 3

1

You only need:

$.ajax({
    type:"POST",
    url: "PostedHere",
    data: { checkedValues: $("#newCheckboxes:checked").serialize() } 
});
// checkedValues: "newCheckboxes=1&newCheckboxes=2" etc..
Sign up to request clarification or add additional context in comments.

1 Comment

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?
0

Using karim79 code idea:

$.post('URL', $('[name="newCheckboxes"]:checked').serializeArray(), function(data){
  //data
});

1 Comment

any idea how i can extract out the info at my URL?
0

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>

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.