2

I want to get the value of the check box in the result variable. But I get the value as 'undefined' in the alert box. What is my mistake?

var result = "";
$("#required").change(function (){
        result= $(".mycheckbox:checked").val();
        alert(result);
        });


<div class=".mycheckbox">
<input id="required" type="checkbox" title="Required" name="required" value="required">
<label for="required">Required</label> 
</div>

4 Answers 4

4

Better to use click event instead of change, as change event works differently depending on browser e.g. IE only fires the change event when the checkbox loses focus.

$(function() {
    $("#required").click(function (){ 
        var result= $(this).attr('checked');  
        alert(result);                
    });   
});

Working Demo

Edit:

I think I may have misunderstood your question. If you only want to display an alert with the checkbox value when the checkbox is checked then something like the following will work

$(function() {
    $("#required").click(function (){ 
        if ($(this).is(':checked')) { 
            var result = $(this).val();  
            alert(result);  
        }              
    }); 
});

Working Demo

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

Comments

4

In you code

result= $(".mycheckbox:checked").val();

I think it should be

result= $("#required").val();

Comments

2

$(".mycheckbox:checked") is not correct, it should be:

$(".mycheckbox :checked")

(note the space)

Your div declaration is also not correct. You shouldn't add the dot in the class name:

<div class="mycheckbox">

Comments

2

You could do something like:

var result = ($("#required").is(':checked')) ? $("#required").val() : false;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.