使用 jQuery 为复选框创建 PHP 友好数组

Posted

技术标签:

【中文标题】使用 jQuery 为复选框创建 PHP 友好数组【英文标题】:Create PHP friendly array for checkboxes with jQuery 【发布时间】:2020-02-05 04:38:15 【问题描述】:

问题的标题可能不是很清楚,我非常感谢任何可以帮助我解决问题的人。这是一种特殊情况,我无法访问 php 文件,也无法在其中更改任何内容,我需要另一种解决方案,但我真的在任何地方都找不到。

这是我的问题: 我有一个 formhidden 值:

<form id="myForm" action="" method="POST">
   <input type="hidden" name="colors[]" value="">
   <input type="submit">
</form>

我还使用javascript 创建了一个array 并带有一些值:

<script>
  var myArray = new Array();
  myArray.push('red');
  myArray.push('yellow');
  myArray.push('green');
</script>

然后我有一个随机的button 某处没有页面(在哪里并不重要)

<button id="myButton">Add to hidden array</button>

所以我想做的是,当我点击按钮id="myButton" 时,我想要一个jQuery 解决方案,将myArray 数组中的所有元素添加到隐藏字段name="colors[]"。 我知道将它们作为JSON string 添加到hidden 字段的值的解决方案,然后在我的PHP 文件中使用json_decode 来读取array。但问题是我无法访问PHP 文件,也无法更改之前编写的函数和逻辑。 PHP 文件接收 arraycheckboxes,因为它通常以标准方式完成,例如:

<input type="checkbox" name="colors[]" value="green">
<input type="checkbox name="colors[]" value="red">
<input type="checkbox name="colors[]" value="yellow">

有没有办法将myArray 放入hidden input 字段的colors[] 数组中而不使用JSON 字符串并且不需要更改PHP 文件中的任何内容,以便PHP 接收和处理字段colors作为checkboxes的普通array

【问题讨论】:

【参考方案1】:

您可以向表单添加多个隐藏输入,每个输入都具有来自数组的不同值。

$("#myButton").click(function() 
    $("#myForm [name='colors[]']").remove();
    $.each(myArray, function() 
        $("#myForm").append($("<input>", 
            type: "hidden",
            name: "colors[]",
            value: this
        ));
    );
);

【讨论】:

以上是关于使用 jQuery 为复选框创建 PHP 友好数组的主要内容,如果未能解决你的问题,请参考以下文章

Jquery数组验证+ php

如果 php 和 jQuery 选中或未选中,则在 php 中动态创建复选框值

如何使用 jquery 从 php 变量中显示 div

使用 Jquery 收集数组中的行 ID,然后为新表查询这些值

使用 jquery 表中的复选框从数组中删除 JavaScript 对象

使用jquery表中的复选框从数组中删除JavaScript对象