How can I use jQuery / JavaScript to find out when the switch is off?

I am trying to use the jquery function to hide / show certain form elements when the checkbox is checked. The same function should also be used to hide / show form elements when checking the switch. The problem is with the switches. My function cannot detect when the switch is disabled so that the div that became visible when it was checked can now be hidden since it is not set. I showed the code below:

<!-- html on one of the pages -->
<fieldset>
  <label for="viaMail">Send offers to my mail</label>
  <input type="checkbox" id="viaMail" class="slide" autocomplete="off">

  <label for="viaEmail">Send offers to my email address</label>
  <input type="checkbox" id="viaEmail" autocomplete="off">

</fieldset>

<div class="viaMail">  <!-- div hidden with css using display: none rule -->
   <!-- input fields for mailing addresses etc --> 
</div>
<!-- end page one html -->

<!-- html on page two -->   
<fieldset>
  <label for="viaMail">Send offers to my mail</label>
  <input type="radio" name="group1" id="viaMail" class="slide" autocomplete="off">

  <label for="viaEmail">Send offers to my email address</label>
  <input type="radio" name="group1" id="viaEmail" autocomplete="off">

</fieldset>

<div class="viaMail">  <!-- div hidden with css using display: none rule -->
   <!-- input fields for mailing addresses etc -->
</div>
 
/* the js function */

ShowHideDiv={
init:function(){
    var radcheck = $(".slide");

//if the input element has the class 'slide' then the value of it 'id' attribute 
//is retrieved and the class which has the same name as the 'id' of the current input
//element is hidden or slided into view - in this case the 'viaMail' class

    radcheck.on("change",function(){
        if($(this).prop('checked')== true) {
            $('body').find("."+$(this).attr('id')).slideDown('slow');
        }
        else {
            $('body').find("."+$(this).attr('id')).slideUp('fast');
        }
    });

}
  }

I tried the function for checkboxes and it works fine. It does not work for switches - the div is “pushed out”, but it does not disappear with “slideUp” when another switch is selected. Truly appreciate your help.

+4
3

if( $(this).prop('checked', true) )
+3

.is(), - .

if( $(this).is(':checked') )

.

, $('body').find("."+$(this).attr('id')) $("." + $(this).attr('id')).

$(function () {
    $('.slide').on("change", function () {
        if ($(this).is(':checked')) {
            $("." + $(this).attr('id')).slideDown('slow');
        } else {
            $("." + $(this).attr('id')).slideUp('fast');
        }
    });
});
+3
if( !$(this).is(':checked') ) // if its unchecked
+1
source

Source: https://habr.com/ru/post/1526310/


All Articles