jeudi 17 novembre 2016

How to immediately un-check a checkbox that has been checked? (Javascript/jQuery)

This may seem weird, but I'm trying to get a checkbox to un-check itself when it's been checked.

The situation: There's a list of steps for a user to complete, and the completed ones have the checkbox grayed out. I want this immediate un-checking behavior when they try to check a step too far ahead.

Javascript:

$(document).on('change', '#checkbox', function () {
    if (this.checked) {
        var routeSectionStepId = this.value;
        var serialNumberId = @ViewBag.Id;
            $.ajax({
                url: '@Url.Action("completestep", "wip")?routeSectionStepId=' + routeSectionStepId + '&serialNumberId=' + serialNumberId,
                success: function(data){
                    if (data.IsOK == false){
                        $('#alertbar').show();
                        $('#alert').html(data.Message);
                        $('#checkbox').prop('checked', false); // HERE
                    } else {
                        window.location.reload(true);
                    }
                },
                error: function(){
                    alert('Error: step could not be completed.');
                },
                complete: function(){
                }
            });
    };
});

Basically what all that is doing is submitting data to the DB when you check the checkbox. If the server comes back with an error (if(data.IsOK == false)...), it displays a message ($(#alertbar').show();...). The problem is, the checkbox is still checked. How do I make it un-check itself when data.IsOK == false?

My attempt // HERE doesn't work. I've also tried this.prop('checked', false); and that doesn't work either.




Aucun commentaire:

Enregistrer un commentaire