0

我有一个带有几个复选框的简单 HTML 表单。我的目标是将此数据(复选框的值)传递给一个 jQuery 函数,并将这些值输入到一个字符串中,该字符串将通过 Ajax 传递给一个 php 脚本。这是我的html:

     <table class="ui-widget-content" border="0" style="width: 100%;">
            <tr>
                <td width="252px;">PVC's Required</td>
                <td align="left">
                        <input type="checkbox" id="pvc" name="pvc" value="abc" />abc<br />
                        <input type="checkbox" id="pvc" name="pvc" value="def" />def<br />
                        <input type="checkbox" id="pvc" name="pvc" value="ghi" />ghi<br />                            
                        <input type="checkbox" id="pvc" name="pvc" value="jkl" />jkl<br />
                        <input type="checkbox" id="pvc" name="pvc" value="NONE" />NONE<br />
                </td>           
            </tr>
</table>

jQuery:

$("#addTechDetails")
                    .button()
                    .click(function(){

                        var pvc = $("#input[ type= 'checkbox']");
                        var pvcData = [];
                        pvc.filter(':checked').each(function(){
                            pvcData.push($(this).val());
                        })
                        pvc=pvcData.join(',');

                        //initial info required to process form
                        var newOrExisting = $("#newOrExisting").val();      
                        var numCircuits = $("#numCircuits").val();          

                            var str = "newOrExisting="+newOrExisting+"&numCircuits="+numCircuits+"&pvc="+pvc;

                                     //ajax request
                            $.ajax({
                                type : "POST",
                                cache : false,
                                url : "ajax/addTechDetails.php",
                                data : str,
                                complete : function(xhr, result){
                                    if (result != "success") return;
                                    var response = xhr.responseText;                                    
                                    $("#result").html(response);
                                }
                            })
            });

即使选中了某些选项,上面的输出也如下所示:'','','','',

4

2 回答 2

1

您不应该在输入选择器的开头使用 # 。那是一个 id 选择器。你应该只有 input[type='checkbox']

..如上所述,复选框不能具有相同的ID。

于 2013-02-11T14:14:16.070 回答
0

您的复选框需要唯一的 ID:

<input type="checkbox" id="pvc1" name="pvc" value="abc" />
<input type="checkbox" id="pvc2" name="pvc" value="def" />
...

此外,此行var pvc = $("#input[ type= 'checkbox']");不应包含前导#,因为这用于通过 Id 进行标识(并且input不是 Id)。

您可以使用以下方法之一:

  • $('input[type="checkbox"]:checked').each()迭代所有选中的元素
  • $('input[name="pvc"]:checked').each()按名称迭代所有复选框
  • $('#pvc'+indexOfiteration).val()直接从Id获取值

文档中有更多选项。

于 2013-02-11T14:30:48.607 回答