1

I have a form with multiple checkboxes. I also have the following code to return the state of these checkboxes.

A) returns "undefined"
B) returns "on" no matter if it is checked or not.
C,D) if I check just C then it also sets D to "true".I only want C to be "true".

$('#button').click(
function() {

    var A = $('#id_a').attr('checked');
    var B = $('#id_b').val();
    var C = $('#id_c').is(':checked');
    var D = $('#id_d').is(':checked');

    $.ajax({
            url: "test.php",
            type: "GET",
            data: "&A="+A+"&B="+B+"&C="+C+"&D="+D,
            success: function(data) {
                $('#display').html(data);   
            }
         });
}

);

Thanks in advance

3
  • 1
    You should post your markup. Commented Aug 1, 2013 at 21:24
  • Use .prop('checked') .. That should get you the right state of the checked property Commented Aug 1, 2013 at 21:28
  • Yeah, check out the differences between attr() and prop() since jQuery 1.7: api.jquery.com/prop vs. api.jquery.com/attr Commented Aug 1, 2013 at 21:30

3 Answers 3

1

jQuery's .prop() method will return a boolean value for "checked".

This is the benefit of .prop() over .attr(), that .prop() returns the type of value that fits the input while .attr() returns what's stored via HTML.

.prop() was added to jQuery in 1.6.

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

Comments

0

Try this:

http://jsfiddle.net/49XDM/1/

var A = $('#id_a').prop('checked');
var B = $('#id_b').prop('checked');
var C = $('#id_c').prop('checked');
var D = $('#id_d').prop('checked');

See http://api.jquery.com/prop/ and check out the section "Attributes vs. Properties". It actually talks about the "checked" property.

Comments

0

if I check just C then it also sets D to "true".I only want C to be "true".

.is(':checked') always returns a boolean, and if you're having issues with it, the problem is elsewhere.

$('#button').on('click', function() {
    var data = {};
    $.each(['a','b','c','d'], function(_,el) {
        data[el.toUpperCase()] = $('#id_'+el).is(':checked');
    });

    $.ajax({
        url : "test.php",
        data: data
    }).done(function(result) {
        $('#display').html(result);
    });
});

FIDDLE

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.