As a Frontend beginner, I am working on implementing toggle switches using HTML, CSS, and Vanilla JavaScript.
Approach:
I am generating an HTML table with multiple rows based on the data from my Django database. Each row contains details like name, id, and status, with a toggle switch for each row. Although I have successfully implemented the toggle switch functionality for a single switch, I am facing an issue with multiple switches.
Challenge:
The problem arises when there are multiple rows and toggle switches, as only the first switch toggles correctly while the others remain unresponsive. Clicking on any toggle switch activates the first one instead of the intended target. My goal is to ensure that each toggle switch functions independently within my Vanilla JavaScript code.
Knowledge:
I understand that assigning unique IDs to each toggle switch is essential, but I am unsure how to achieve this dynamically without knowing the exact number of rows beforehand and how to handle these IDs effectively in my JavaScript code.
Code Snippet:
var myswitch = document.querySelectorAll(".idm-switch_div .toggle");
myswitch.forEach((element) => {
element.addEventListener("click", function () {
var isChecked = document.querySelector(".toggle-checkbox").checked;
localStorage.setItem("checkstate", !isChecked);
console.log(!isChecked);
});
});
.toggle {
position: relative;
display: inline-block;
... (CSS code continues)
}
/* Checkbox styling and behavior */
... (CSS code continues)
/* Toggle switch structure */
<div class="idm-switch_div div-container">
<input type="checkbox" id="switch" class="toggle-checkbox" />
<label for="switch" class="toggle"> </label>
</div>
If you have any advice or solutions to offer, I would greatly appreciate your help. Thank you for your assistance!