Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

prevent double click on button in javascript

<script type="text/javascript">
    $(document).ready(function () {
        $("#submit").on("click", function () {
            $(this).attr('disabled', true);
            var taskid = num;
            var loadnew = 1;
            var guessnum = $("input[name=guessnum]:checked").val();
            if (guessnum != 1 && guessnum != 2) {
                alert("You could not submit an empty answer");
                loadnew = 0;
                location.href = "/minions/peerprediction1.php";
            }
            else if (loadnew == 1) {
                finishedTask += 1;
            }
            var starttime = $("#timestart").val();
            var timecost = starttime;
            $.ajax({
                type: "post",
                url: "GameMysql.php",
                data: "taskid=" + taskid + "&guessnum=" + guessnum + "&effort=" + effort + "&finishedTask=" + finishedTask + "&time=" + timecost,
                success: function (data) {
                }
            });
        });
    });

</script>
<form>
    <a class="button" id="submit"><span>&#10003</span>Submit report</a>
</form>

I want to make sure the form with same answers do not submit twice, and disable the button, but it does not truly work. For I click it twice the finished task number increased by 2 I already see the answer here Prevent double submission of forms in jQuery and tried, but still could not make it work

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the button element, it will provide the functionality you are after. It can be styled to look like an anchor. Less issues trying to get it working as intended across all browsers.

$("#submit").on("click",function(){    
    $(this).attr('disabled', true);
    console.log('disabled');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" id="submit"> <span>&#10003</span> Submit report</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...