在jQuery中序列化复选框 [英] serializing checkboxes in jQuery

查看:184
本文介绍了在jQuery中序列化复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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>
   }

$ b b

javascript

javascript

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

createb.php is只是测试表单

at the moment createb.php is just testing the form

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

问题是,serialize函数只看到第一个复选框,并指示它是否已被选中,它没有看到任何其他复选框。是否有人知道为什么其他复选框不会被序列化和做什么呢?

The Problem is that the serialize function only sees the first checkbox and indicates whether it has been checked or not. It does not see any of the other check boxes. Does anybody have an idea why the other check boxes do not get serialized and what to do about it?

感谢
David

Thanks David

推荐答案

来自 Jquery文档的报价:只有成功的控件被序列化到字符串(当使用$(form).serialize())或数组($(form).serializeArray())。复选框和单选按钮(radio或checkbox类型的输入)的值仅在选中时才包含。

Quote from Jquery documentation: Only "successful controls" are serialized to the string (when using $(form).serialize()) or to array($(form).serializeArray()). Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked.

您可以使用类似这样的方法来模拟类似于您期望的行为:

You can use something like this to emulate behavior similar to what you expect:

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

这篇关于在jQuery中序列化复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆