tags:

views:

95

answers:

5

hi, 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>
A: 

first you only get the first checkd checkbox (:checked), second what is val()? shouldn't that mean value()?

other information that would be useful: what language/toolkit are you using – mootools, jquery, …?

knittl
.val() is the proper way to get a value on an imput.
Tom Hubbard
+3  A: 

In you code

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

I think it should be

result= $("#required").val();
teerapap
+1  A: 

$(".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">
Philippe Leybaert
+2  A: 

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

Russ Cam
+1  A: 

You could do something like:

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