简体   繁体   中英

How to change toggle switch with JavaScript

I have designed a toggle-switch with CSS and HTML but I want to be able to toggle/change the toggle switch with javascript.

How do I go about this, you can check out the code in this jsfiddle link

<div id="activate" class="toggle-switch" data-ts-color="green">
  <label for="ts4" class="ts-label">Activate Account</label>
  <input id="ts4" type="checkbox" hidden="hidden">
  <label for="ts4" class="ts-helper"></label>
</div>

My Javascript: but it does not work

if (false) {
    // turn toggle switch off
    $("#ts4").attr("checked", false);
    $('#activate').click();
} else {
    // turn toggle switch off
    $('#ts4').attr("checked", true);
    $('#activate').click();
}

I want to be able to toggle the toggle switch programmatically when? I get a value from the database

Two things:

1) Syntax in javascript, you didn't close "if" brackets. 2) You didn't check use of jQuery in JSFiddle. It won't work without that. That's working example:

if (false) {
  // turn toggle switch off
  $("#ts4").attr("checked", false);
  $('#activate').click();
} else {
  // turn toggle switch ON
  $('#ts4').attr("checked", true);
  $('#activate').click();
}

https://jsfiddle.net/a99dkxp1/4/

You should use prop() instead of attr() , since attr only sets the attribute with the given value without any "intellingence" and checked is a marker attribute, which does not need to have a value at all. prop() has such "intelligence" implemented.

Your if statement will always go the "else" way.

if(false) {
     // unreachable code
}else {
}

just like

if(true) {
}else {
    // unreachable code
}

Change it to

 if(property == false) {...

or even better

if(!property) {...

or inline the condition and drop the if-else

$("#ts4").attr("checked", !property); 
$('#activate').click(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM