Home > Mobile >  How to get the switch toggle switch current state(true/false) onload in Javascript
How to get the switch toggle switch current state(true/false) onload in Javascript

Time:10-27

I have a multiple switch toggle which is coming from PHP/Mysql code, I want to show the div in that toggle which is currently ON.

Also, I want to show/hide div when that toggle switch on/off

enter image description here

My Php Code:

  <li>
    <?php echo $_ship_method_value['shipping_title'];?>
    <label class="switch">
      <!-- Toggled Case -->
      <input type="checkbox" id="toggd" name="toggle" value="<? echo $_ship_method_value['shipping_id']; ?>" class='cmn-toggle cmn-toggle-round' data-switchery <? if(array_key_exists("shipping_available",$_ship_method_value)) echo 'checked'; ?> /> 
       <span class="slider round hide-off"></span>
  </li>

      <div class="show-hide">
         <p>Want to show this div ;-)</p>
     </div> 
  
 

My jQuery Code

   $('input[name=toggle]').change(function(){
          var mode = $(this).prop('checked');
            if(mode == true){
              $(".show-hide").show();
            }else{
              $(".show-hide").hide();
            }
          });'

but this code is only working on click of toggle for the single toggle event.

Please help me to find the solution. Thank you!

CodePudding user response:

 $('.toggle_check_box').change(function(){
          var mode = $(this).prop('checked');
            if(mode == true){
              $(".show-hide").show();
            }else{
              $(".show-hide").hide();
            }
          });

you can apply class for your checkbox and use like this.. This will toggle div on all switch button

CodePudding user response:

 $('body').on('change', 'input[name=toggle]', function() {
    var mode = $(this).prop('checked');
    if (mode == true) {
        $(".show-hide").show();
    } else {
        $(".show-hide").hide();
    }
});

** Update **

If div is located next to li then the bellow code will work for you.

 $('body').on('change', 'input[name=toggle]', function() {
    var mode = $(this).prop('checked');
    if (mode == true) {
       $(this).closest("li").next(".show-hide").show();
    } else {
       $(this).closest("li").next(".show-hide").hide();
    }
});
  • Related