Toggle Switch Button

Hi there, I’m working on a Library App for TOP and I need some help.

I’m trying to add a toggle button inside a table that I created inside a JS function and I want to switch between ‘yes’ and ‘no’ every time the user clicks on it.

Right now it only works once and when I click the button a second time it won’t fire the event.

This is my github repo: GitHub - 1987mat/LibraryApp.

Thanks!

try adding a condition for both states. if yes then no if no then yes

you probably want something like this

let clicked = false;
button.addEventListener('click', () => {
clicked = !clicked;
if (clicked) {
doThis;
return
}
doThisWhenFalse;
})

I tried something like this but it doesn’t work:

    if(e.target.classList.contains('toggle')) {
    let toggle = e.target;
    toggle.addEventListener('click', () => {
        if (e.target.parentElement.previousElementSibling.innerHTML = 'yes') {
            e.target.parentElement.previousElementSibling.innerHTML = 'no'; 

        } else if (e.target.parentElement.previousElementSibling.innerHTML = 'no') {
            e.target.parentElement.previousElementSibling.innerHTML = 'yes';
        }
    })

You are redeclaring the toggle variable every time the handler runs.

It’s also not “tied” to a specific book, so if you just make toggle a top-level variable you would lose the state on refresh. You would also get a bug where toggling one book would affect the toggle logic of another book. So you have to update the toggle state for each book’s data (i.e. the read yes/no value).

In addition to the above, you’ve used the assignment operator (=) in your if statements, not a comparison operator (== or ===).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.