简体   繁体   中英

Turn feature ON or OFF via checkbox

I have a feature on my video to play next video in loop, this feature would be toggled on or off via checkbox. I'm using alerts to verify "play next" is checkbox is checked and "dont play next" is checkbox is not checked. I want the checkbox to be checked and play next by default (on page load) and always listen after that.

The problem I'm having now is that when I get the "dont play next" alert the video still plays the next video on end.

My JavaScript

$(document).ready(function() {
  $(function() {
    chckplynext();
    $("#chkbox1").change(chckplynext);
  });

  function chckplynext() {
    if ($("#chkbox1").is(':checked')) {
      alert("play next");
      $("#myvid").on("ended", function() {
        window.location.href = "<?php echo'now-watching.php?nMe='.$usTitle1.'&nmov='.$usId1.'' ?>";
      });
    } else {
      alert(" Dont play next");
    }
  }
});

Without a working example it's hard to know exactly which framework or libraries you are using. However, it looks like you are binding the event multiple times.

You would benefit from restructuring your code

$(document).ready(function() {
    $("#myvid").on("ended", function() {
        if ($("#chkbox1").is(':checked')) {
            alert("play next");
            window.location.href = "<?php echo'now-watching.php?nMe='.$usTitle1.'&nmov='.$usId1.'' ?>";
        } else {
            alert(" Dont play next");
        }
    });
});

The change is that we are binding the event once, which will always fire when the video ends. It is at this point that we can check whether to play the next video or not.

You could achieve a similar result with your original structure by adding $("#myvid").off("ended") into your else block.

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