开发者

How to pass checkbox values into an array using jQuery?

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

              }
     开发者_JAVA百科    });


You only need:

$.ajax({
    type:"POST",
    url: "PostedHere",
    data: { checkedValues: $("#newCheckboxes:checked").serialize() } 
});
// checkedValues: "newCheckboxes=1&newCheckboxes=2" etc..


Using karim79 code idea:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜