【问题标题】:Add/append value from checkboxes to hidden field将复选框中的值添加/附加到隐藏字段
【发布时间】:2017-12-12 14:51:05
【问题描述】:

我有 4 个复选框和一个隐藏字段,其中包含四个电子邮件地址中的任何一个,具体取决于已选择的选项。如果未选中相应的复选框,则电子邮件地址也需要从隐藏字段中删除。

我不知道如何编写这样的函数,希望有人能指出我正确的方向,或者有人可以为我编写脚本吗?

【问题讨论】:

  • 这是否意味着可以选中多个复选框?如果是这样,隐藏的输入字段是否会包含所有值?
  • 是的,没错。 @MehrdadDastgir

标签: jquery checkbox hidden-field


【解决方案1】:

假设你有以下html:

<input type="checkbox" name="email[]" value="email1@example.com">
<input type="checkbox" name="email[]" value="email2@example.com">
<input type="checkbox" name="email[]" value="email3@example.com">
<input type="checkbox" name="email[]" value="email4@example.com">
<input id="hidden" type="hidden" name="hidden">

下面的 jQuery 会给你结果。

        $(function() {
        // listen for changes on the checkboxes
        $('input[name="email[]"]').change(function() {
            // have an empty array to store the values in
            let values = [];
            // check each checked checkbox and store the value in array
            $.each($('input[name="email[]"]:checked'), function(){
                values.push($(this).val());
            });
            // convert the array to string and store the value in hidden input field
            $('#hidden').val(values.toString());
        });
    });

请注意,这是一个关于如何克服您的问题的粗略解决方案,并且可以简化和重构。将此视为概念证明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多