JSFiddle - React, Tailwind, and code Playground

by william

HTML

<form id="form">
    <input type="checkbox" value="value1" class="myCheckboxClass" /> value 1 <br />
    <input type="checkbox" value="value2" class="myCheckboxClass" /> value 2 <br />
    <input type="checkbox" value="value3" class="myCheckboxClass" /> value 3 <br />
    <input type="checkbox" value="value4" class="myCheckboxClass" /> value 4 <br />
    <input type="checkbox" value="value5" class="myCheckboxClass" /> value 5 <br />
    
    <input name="IDList[]" type="hidden" id="IDList" value="" />
    
    <input type="submit" />
</form>

JavaScript

$('#IDList').data('value', []);

$(".myCheckboxClass").change(function() {
    var list = $('#IDList').data('value');

    if ($(this).is(":checked")) {
        list.push($(this).val());
    } else {
        var index = list.indexOf($(this).val());
        list.splice(index, 1);
    }
    $('#IDList').val(list);

    console.log($('#IDList').data('value'));
    console.log($('#IDList').val());
});

$('#form').submit(function() {
    var list = $('input.myCheckboxClass:checked', this).map(function() {
        return $(this).val();
    }).get();
    
    $('#IDList').val(list);
    
    console.log($('#IDList').val());
    return false;
});