De/Selecting Checkboxes with jQuery

De/Selecting Checkboxes with jQuery

 

The jQuery code below is an example on how to add and remove checkbox values to/from an array. The array can then be added to a DOM object/element and used in subsequent processing, like an SQL (dbfield in ‘${param.newElement}’) statement.

<html>
<head>
<title>Page Title</title>
</head>

<body>
<h2>Page Header</h2>
<form>
<input name="checkboxname" value="1" onclick="setCheckbox()" />Checkbox #1
<input name="checkboxname" value="2" onclick="setCheckbox()" />Checkbox #2
<input name="checkboxname" value="3" onclick="setCheckbox()" />Checkbox #3
</form>
</body>
</html>

<script>
var checkboxselections = [];

function setCheckbox() {
    // ADDS SELECTED CHECKBOX TO AN ARRAY WHEN CHECKED
    $("input:checkbox[name=checkboxname]:checked").each(function() {
        if(checkboxselections.indexOf($(this).val()) < 0) { 
            checkboxselections.push($(this).val()); 
        } 
    }); 

    // REMOVES SELECTED CHECKBOX TO AN ARRAY WHEN DESELECTED 
    $("input:checkbox[name=checkboxname]:not(:checked)").each(function() { 
        ndx = checkboxselections.indexOf($(this).val()); 
        if(ndx > -1) {
            checkboxselections .splice(ndx,1);
        }
    });

    //document.getElementById('newElement').value can now be passed to an SQL statement on a submit.
    document.getElementById('newElement').value = checkboxselections.toString();   

}

</script>

jQuery Checkboxes