Search code examples
jqueryajax

Ajax call is called even if the switch is in off status


I have a bootstrap switch and a jquery script with an ajax call that should start only if the switch is checked. What happen is that, when I load the page the first time everything is fine (the switch is off and the ajax call doesn't start). If I click on the switch the ajax call works. If I click again to off the switch, the ajax call continue to works. It should stop. Below you can find the script. Why this is happening?

<input class="form-check-input" type="checkbox" role="switch" id="right" >

<script>
$(document).ready(function(){
  var switchStatus = false;
  $('#right').on('change', function() {
    console.log($('#right').is(':checked'));
    if ($(this).is(':checked')) {
      switchStatus = $(this).is(':checked');
      if(switchStatus==true){
        $('input[id*="opr_"]').on("keyup change", function(e) {
          var key_opr = $(this).attr('id');
          //console.log(key_opr);
          var opr = $(this).val();
          //console.log(opr);
          $.ajax({
            url: 'check.php',
            type: 'POST',
            data: jQuery.param({ id_game: "<?=$id_game;?>", opr : opr, key_opr : key_opr}) ,
            success:function(data) {
              //console.log(data);
              if(data==1){
                $("#"+key_opr).removeClass('td_fill').removeClass('td_wrong').addClass('td_good'); 
              }else{
                $("#"+key_opr).removeClass('td_fill').removeClass('td_good').addClass('td_wrong'); 
              }
            }
          });
        });
      }
    }else{
      switchStatus = $(this).is(':checked');
    }
  });
});

Solution

  • else {
             // Turn off the event listener for the 'opr_' inputs when the switch is turned off
             $('input[id*="opr_"]').off("keyup change");
          }
    

    When the switch is turned off the event listener is removed using the .off() method. This prevents the AJAX call from being initiated as there's no longer any listener on the input[id*="opr_"] elements for those events.