简体   繁体   中英

JS countdown doesn't work on button click

I have a problem implementing JS redirect countdown... Here you can see button html, when I click on it it should start redirect countdown:

<footer>
    <button type="submit" class="btn btn-primary">
        <i class="fa fa-refresh"></i> Reset Password
    </button>
</footer>

And here is js:

$("button").click(function() {
    var count = 3;
    var countdown = setInterval(function(){
    $("#redirect").text(count);
        if (count == 0) {
            clearInterval(countdown);
            window.open('index.php', "_self");

        }
    count--;
    }, 1000);
});

The problem is that when I'm clicking on button it doesn't do anything not counting not redirecting.. If I move script out of button click event then it works properly.. What am I missing and doesn't understand here?

Thanks..

Your button is a submit button, ie it will submit the current form and will definitely refresh the page, which will result in your script being terminated.

You should add e.preventDefault() if you want to avoid the default behavior of the submit button

$("button").click(function(e) {
    var count = 3;
    var $that = $(this);
    var countdown = setInterval(function(){
        $("#redirect").text(count);
        if (count == 0) {
            clearInterval(countdown);

            window.open('index.php', "_self");

            // submit now
            $that.closest('form').submit();
        }
        count--;
    }, 1000);
    e.preventDefault();
});

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