Getting value of selected checkbox with jquery from checkboxes without id's

http://stackoverflow.com/questions/17050412/getting-value-of-selected-checkbox-with-jquery-from-checkboxes-without-ids

by Akram kamal

HTML

<hr />
<output>0 are checked<p>No Values</p></output>
<hr />
<input type="checkbox" name="cjk" id="cjk" value="0" />

CSS

output {
    display: block;
    padding: 1em;
}

JavaScript

var checked, checkedValues = new Array();
$(document).on("change", "input[type=checkbox]", function(e) {
    
    checked = $("input[type=checkbox]:checked");
    checkedValues = checked.map(function(i) { return $(this).val() }).get();
    
    //    simply shows whats been tagged in output HTML area
    $("output").html(checked.length + " are checked");
    if (checked.length) {
        var str = checkedValues.join();
        $("output").append($("<p />", { text: "Values: " + str }));
    }
    else {
        $("output").append($("<p />", { text: "No Values" }));
    }
    
    //    shows the variables in the developer console
    console.log('checked', checked);
    console.log('checkedValues', checkedValues);
});


/*    dynamically add checkboxes to page for 20 seconds    */
var i = 1, tmr;
tmr = setInterval(function() {
    $("body").append($("<input />", { type: "checkbox", value: i }));
    i++;
    if (i >= 20) clearInterval(tmr);
}, 1000);