buttonset: value of checkbox group

this shows that jquery val() only gives the value of the first item in a selection! cannot be used to get the value of a checkbox group.

by hrabinowitz

HTML

<form id="myform">
    <input type="checkbox" value="1" name="choices">value1</input>
    <input type="checkbox" value="2" name="choices">value2</input>
    <input type="checkbox" value="3" name="choices">value3</input>
    <input type="checkbox" value="4" name="choices">value4</input>
    <input type="checkbox" value="5" name="choices">value5</input>
    <br>
    <input type="radio" value="1" name="rad">value1</input>
    <input type="radio" value="2" name="rad">value2</input>
    <input type="radio" value="3" name="rad">value3</input>
    <input type="radio" value="4" name="rad">value4</input>
    <input type="radio" value="5" name="rad">value5</input>
</form>

JavaScript

$('form#myform').on('change', function() {
    console.log("value of form is ", $('form#myform').val());                       
    console.log("value of checkboxes is ", $('input[name="choices"]').val());    
    console.log("value of checked checkboxes is ", $('input[name="choices"]:checked').val());

    // following is the only way that works!
    var checkboxValues = $('input[name="choices"]:checked').map(function() {
        return $(this).val();
    }).get();
    console.log("value of checkbox group using map is ", checkboxValues);
    
    // following NOT good
    console.log("bad value of rad is ", $('input[name="rad"]').val());
    // following good:
    console.log("good value of rad is ", $('input[name="rad"]:checked').val());
    
    $.post("blah.php", { 'mychoices': checkboxValues });
});