Acubi
Acubi

Reputation: 2783

alertBox doesn't display when ticking checkbox

I can't see any error in my code. However, the Alertbox doesn't display when checkbox is ticking.

Is there anyone can help me? Thanks in advance.

 <script type="text/javascript" language="javascript" src="jquery/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" language="javascript">
    $(function(){

              if($("#checkkBoxId").attr("checked"))
                        {
                            alert("Checked");
                        }
                        else
                        {
                            alert("Unchecked");
                        }

    });


    </script>
    </head>

    <body>

        <p><input id="checkkBoxId" type="checkbox">Enable</p>
    </body>

Upvotes: 2

Views: 166

Answers (4)

Agustin Meriles
Agustin Meriles

Reputation: 4854

You have to attach the function to the checkbox's click event.

$("#checkkBoxId").change(function(){

          if($(this).prop("checked"))
                    {
                        alert("Checked");
                    }
                    else
                    {
                        alert("Unchecked");
                    }

});

Upvotes: -2

ThiefMaster
ThiefMaster

Reputation: 318488

Your code executes exactly once when the DOM is ready. So any changes will not trigger it.

Here's the proper solution:

$(function () {
    $('#checkkBoxId').change(function () {
        if ($("#checkkBoxId").prop('checked')) {
            alert("Checked");
        } else {
            alert("Unchecked");
        }
    });
});

Upvotes: 0

Alex Pliutau
Alex Pliutau

Reputation: 21957

$(document).ready(function() {
    $('#checkkBoxId').change(function() {
        if ($(this).prop('checked')) {
            alert('checked');
        } else {
            alert('not checked');
        }
    });
});

Upvotes: 4

Manuel van Rijn
Manuel van Rijn

Reputation: 10305

you need to bind the click event on the checkbox like

$("#checkkBoxId").click(function() {
    if($(this).attr("checked")) {
        alert("Checked");
    }
    else {
        alert("Unchecked");
    }
}):

Upvotes: 2

Related Questions