1

My code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="jquery.js"></script>
<script>
$(function(){
    $("body").on("click",".mes_sel",function(){
        if($(".mes_sel:checked").length==0){
            alert("Checked");
        }
        else alert("Not Checked");
    });
});
</script></head>
<body>
<input type="checkbox" class="mes_sel">
</body>
</html>

It is alerting checked when the textbox is unchecked because onclick is running before the checking of checkbox.How can i make the click event to run after checking/unchecking of the input

3 Answers 3

1

Use change for that:

$(function(){
    $(".mes_sel").on("change", function(){
        if($(this).is(':checked')){
            alert("Checked");
        } else {
            alert("Not Checked");
        }
    });
});​

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

Try this instead:

$("body").on("click", ".mes_sel", function() {
    if ($(this).is(":checked")) {
        alert("Checked");
    }
    else alert("Not Checked");
});​

jsFiddle example.

1 Comment

So help me in decide which is better yours or Anytrat
0

I ran into this problem a while back - I also found that different browsers handled this differently. Chrome was the worst offender, if I remember correctly.

This isn't necessarily the best solution, but you could attach a custom attribute to each checkbox, say "isChecked", and then base your function off this attribute like so:

if ($("mes_sel").attr("isChecked") == "true") { ... }

Like I said, not the best solution as you will have to manually flip the "isChecked" attribute in order to stay consistent with the actual checked value of the checkbox, but it will work if nothing more elegant will work for you.

If you'd like an example of this , check out this jsFiddle:

http://jsfiddle.net/NathanFriend/GAP2j/

This turns regular radio buttons into "toggleable" radio buttons - I was forced to use this custom attribute method because of the different way browsers execute onclick events.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.