I dynamically created a set of checkboxes and labels in plain JavaScript. This works fine and the checkboxes are displayed:
const label = document.createElement("label");
const checkbox = document.createElement("input");
const description = document.createTextNode(course[i].name);
checkbox.type = "checkbox";
checkbox.id = "checkbox-" + course[i].name;
checkbox.value = course[i].name;
label.appendChild(checkbox);
label.appendChild(description);
const mainDiv = document.getElementById("main");
mainDiv.appendChild(label);
However, when I click a button elsewhere on the screen, I need that eventHandler to reset all of the checkbox values so that they are all unchecked. I tried both of the following two options. None give me browser errors, but neither have the desired effect:
for (let i = 0, l = allItems.length; i < l; ++i) {
document.getElementById("checkbox-" + allItems[i].name).checked = false;
}
$("input[type=checkbox]").each(function () {
this.checked = false;
});
Inside the browser console I can retrieve the value of "checked", and set it to false, but the UI does not reflect this change. I looked all over on StackOverflow. Although there were people within similar questions, I could not get the suggested solutions to work for me.
You have to uncheck the check boxes inside the button's event handler function:
$('#reset').click(function(){
$("input[type=checkbox]").each(function () {
this.checked = false;
});
});
Demo:
var course = [{name: 'TestCourse1'},{name: 'TestCourse2'},{name: 'TestCourse3'}] for(var i = 0; i < course.length; i++){ const label = document.createElement("label"); const checkbox = document.createElement("input"); const description = document.createTextNode(course[i].name); checkbox.type = "checkbox"; checkbox.id = "checkbox-" + course[i].name; checkbox.value = course[i].name; label.appendChild(checkbox); label.appendChild(description); const mainDiv = document.getElementById("main"); mainDiv.appendChild(label); } $('#reset').click(function(){ $("input[type=checkbox]").each(function () { this.checked = false; }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="main"></div> <button id="reset">Reset</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.