Function to auto-populate form elements

by lasha

HTML

<div class="form-container">
    <label>label 01<input type="checkbox" name="item1" value="Item 1"></label><br>
    <label>label 02<input type="checkbox" name="item2" value="Item 2" checked></label><br>
    <label>label 03<input type="checkbox" name="item3" value="Item 3"></label><br>
    <label>label 04<input type="checkbox" name="item4" value="Item 4"></label><br>
    <label>label 05<input type="checkbox" name="item5" value="Item 5"></label>
</div>

JavaScript

$(".form-container").on("change", "input", function(){
    console.log( $(this) )
});

function populateCheckboxes($inputs, data){
    var $inputs = $inputs.length === 1 ? $inputs.find("input") : $inputs;
    $inputs.prop("checked", false); // remove all checks
    $inputs.each(function(i, el){
        var $this = $(this),
            nameVal = $this.attr("name");
        
        if(data.hasOwnProperty(nameVal)){
            $this.prop("checked", true).trigger("change");
        }
    });
}

populateCheckboxes($(".form-container"), { // this object contains only the checkboxes that are to set to checked
    item1: true,
    item3: true,
    item4: true
});