Serializing checkboxes in jQuery

I have a jQuery form in which I create a series of checkboxes:

<?php <form method="post" id="b-form" action="../createb.php"> for ($i=0; $i<$request_count; $i++){ <div class="request-check"> <table> <tr> <td><input type="checkbox" name="show_request[]" value="request".$i." checked="checked"/>select request</td> </tr> </table> </div> } 

Javascript

 $.ajax({ type: 'POST', url: '../createb.php', data: $('#b-form').serialize(), success: function (msg){ alert(msg); } }) 

createb.php is currently just testing the form

  $requests = $_POST['show_request']; $request_count = count($requests); echo 'count: '.$request_count; echo $requests[0]; 

The problem is that the serialization function sees only the first flag and indicates whether it has been checked or not. He does not see any other flags. Does anyone have an idea why other flags are not serialized and what to do about it?

Thanks david

+6
jquery checkbox
source share
4 answers

Well, that’s true, since you have all the flags with the name name and any id to separate them.

try to create them as:

 <input type = "checkbox" id = "ckb_<?php echo $i ?>" name = "ckb_<?php echo $i ?>_show_request[]" value = "request".$i." checked = "checked"/> select request 

I'm sure $('#b-form').serialize() now generates all the flags you want them

+3
source share

Quote from the JQuery Documentation : only the successful control string is serialized to a string (when using $ (form) .serialize ()) or to an array ($ (form) .serializeArray ()). Values ​​from checkboxes and radio buttons (radio or checkbox inputs) are only included if they are checked.

You can use something like this to emulate behavior like expected:

 var myCbValuesArray = $("input:checkbox").map(function(){ return $(this).is(":checked"); }).get(); 
+3
source share

Your selector is wrong.

Try:

 $('#b-form input:checkbox').serialize() 

To get only verified input, use:

 $('#b-form input:checkbox:checked').serialize() 
+2
source share

This will work for you.

You can get selected checkbox values.

  $("input[type='checkbox']:checked").serialize(); 
+1
source share

All Articles