将值从复选框添加/追加到隐藏字段 [英] Add/append value from checkboxes to hidden field

查看:86
本文介绍了将值从复选框添加/追加到隐藏字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 4 checkboxes and one hidden field that will contain any one of four email addresses, depending on which options have been selected. The email address will also need to be removed from the hidden field if the corresponding checkbox is unchecked.

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

I have no idea how to write such function and was hoping somebody could atleast point me in the right direction or could someone write the script for me please?

推荐答案

假定您具有以下html:

Assuming you have the following 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将为您提供结果.

The following jQuery will give you the results.

        $(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());
        });
    });

请注意,这是解决问题的粗略解决方案,可以简化和重构.将此视为概念证明.

please note this is a rough solution on how to overcome your problem and can be simplified and refactored. Treat this as a proof of concept.

这篇关于将值从复选框添加/追加到隐藏字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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