我正在尝试选择一系列选定的复选框并在输入字段内创建一个逗号分隔的列表。这有点超出了我的 jQuery 技能范围。
以下是 HTML 示例:
<input type="checkbox" value="Bill" id="CAT_Custom_173676_0" name="CAT_Custom_173676" />Bill<br />
<input type="checkbox" value="Dan" id="CAT_Custom_173676_1" name="CAT_Custom_173676" />Dan<br />
<input type="checkbox" value="Francis" id="CAT_Custom_173676_2" name="CAT_Custom_173676" />Francis<br />
我需要从这些复选框中获取值并将它们插入到此字段中
<input type="text" class="cat_textbox" id="CAT_Custom_172786" name="CAT_Custom_172786" maxlength="1024" />
因此,如果选中上述所有复选框,则输入字段的值将为“Bill,Dan,Francis”。
提交表单时可能会发生此事件。
如有任何帮助,我们将不胜感激。
最佳答案
您可以使用map()在这里创建一个新的 jQuery 对象,其中包含选中的复选框的值,然后使用 get()获取数组,然后使用 join(",") nb 创建这些值的逗号分隔字符串:
var arr = $("input:checked").map(function () { return this.value; });
$("#CAT_Custom_172786").val(arr.get().join(","));
nb:您实际上可以省略 join(),因为转换为字符串的数组会自动以逗号分隔连接。个人喜好在这里发挥作用。
关于jquery - 需要从选定的复选框中获取值并将其放入输入文件中,并用逗号分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3522216/