Home > Enterprise >  Change a toggle switch check to true or false
Change a toggle switch check to true or false

Time:12-07

I have a toggle switch like this one: enter image description here

And the Active label is coming from a database. I want this button to be changed to true if it's active.

This is what I've tried so far:

HTML

<input onclick='toggleStatus(this)' type='checkbox' id='{{ db.id }}' name='{{ db.id }}'>
<label id='user-status-toggle' for='{{ db.id }}'>{{ db.status }}</label>

JavaScript

function toggleStatus(radio) {
    var toggle = document.getElementById('user-status-toggle');

    if (radio.checked) {
        toggle.textContent = "Active";
        radio.checked = true;
    } else {
        toggle.textContent = "Inactive";
        radio.checked = false;
    }
}

It's working, but only when I interact with the button. When I first visit the page, it's always toggled off, even if the status is Active. Note that I may have multiple buttons and their status may vary between Active and Inactive.

So how should I do this?

CodePudding user response:

I fixed it by checking if the db.status === "Active" first with an if-else statement in PHP:

if (db.status === "Active")
{
    return <input checked onClick=toggleStatus(this)'>
}
else
{
    return <input onClick=toggleStatus(this)'>
}

CodePudding user response:

You can set initial checked on your <input />

just add checked attribute.

for example,

// if this one is what you want initial checked..
<input checked onclick='toggleStatus(this)' type='checkbox' id='{{ db.id }}' name='{{ db.id }}'>
<label for='{{ db.id }}'>{{ db.status }}</label>
<input onclick='toggleStatus(this)' type='checkbox' id='{{ db.id }}' name='{{ db.id }}'>
<label for='{{ db.id }}'>{{ db.status }}</label>

I don't know about PHP well, but I guess it would be work..

// if this one is what you want initial checked..
<input checked='{{ db.textContent === "Active" }}' onclick='toggleStatus(this)' type='checkbox' id='{{ db.id }}' name='{{ db.id }}'>
<label for='{{ db.id }}'>{{ db.status }}</label>

  • Related