Search code examples
jquerycheckboxhidden-field

Add/append value from checkboxes to hidden field


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?


Solution

  • 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.