jeudi 13 septembre 2018

How to make checkbox events from dynamically created checkbox javascript

I have three parameters namely model, destination and criteria. Whenever the user chooses a model from the dropdown list, where the destination and criteria is dependent, dynamic checkboxes for the destination is shown. And when a user tick a destination, its specific criteria will show. This is a follow up question: How to display multiple list of checkboxes dynamically on dropdown list

<script type="text/javascript">
    function populate(model, destination) {
        var mod = document.getElementById(model);
        var des = document.getElementById(destination);
        des.innerHTML = "";
        if (mod.value == "model-a") {
            var optionArray = ["Model-A.1", "Model-A.2", "Model-A.3"];
        } else if (mod.value == "model-b") {
            var optionArray = ["Model-B.1", "Model-B.2", "Model-B.3"];
        } else if (mod.value == "model-c") {
            var optionArray = ["Model-C.1", "Model-C.2", "Model-C.3"];
    }

    for (var option in optionArray) {
        if (optionArray.hasOwnProperty(option)) {
            var pair = optionArray[option];
            var checkbox = document.createElement("input");
            checkbox.type = "checkbox";
            checkbox.name = pair;
            checkbox.value = pair;
            des.appendChild(checkbox);
    
            var label = document.createElement('label')
            label.htmlFor = pair;
            label.appendChild(document.createTextNode(pair));

            des.appendChild(label);
            des.appendChild(document.createElement("br"));    
        }
    }
}
</script>
<!DOCTYPE html>
<html>
<body>

SELECT MODEL:
<select id="model" name="model" onchange="populate(this.id, 'destination')">
   <option value=""></option>
   <option value="model-a">MODEL-A</option>
   <option value="model-b">MODEL-B</option>
   <option value="model-c">MODEL-C</option>
</select>
<hr />
SELECT DESTINATION:
<div id="destination"></div>
<hr />
</body>
</html>

Can you help me with adding such events. Iam new and still learning javascript.




Aucun commentaire:

Enregistrer un commentaire