Add/append value from checkboxes to hidden field

孤街醉人 提交于 2020-07-22 09:26:28

问题


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?


回答1:


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">

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.



来源:https://stackoverflow.com/questions/47775442/add-append-value-from-checkboxes-to-hidden-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!