Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Change a toggle switch check to true or false

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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)'>
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda