Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!