Sending checkbox values with JavaScript

This example shows how to collect values from the checked checkboxes. JavaScript function uses getElementsByTagName method to collect all input objects of the HTML page (HTML form is not needed). With for loop, every collected object is tested against type and checked property. If type is checkbox and checkbox is checked then value will be concatenated to the final string. String has URL form and can be used with window.location.href property to send checkbox values.

Value CheckBox
1
2
3
4
5
6

Here is JavaScript function (passes JSLint verification):

// function will loop through all input tags and create
// url string from checked checkboxes
function checkbox_test() {
    var counter = 0, // counter for checked checkboxes
        i = 0,       // loop variable
        url = '',    // final url string
        // get a collection of objects with the specified 'input' TAGNAME
        input_obj = document.getElementsByTagName('input');
    // loop through all collected objects
    for (i = 0; i < input_obj.length; i++) {
        // if input object is checkbox and checkbox is checked then ...
        if (input_obj[i].type === 'checkbox' && input_obj[i].checked === true) {
            // ... increase counter and concatenate checkbox value to the url string
            counter++;
            url = url + '&c=' + input_obj[i].value;
        }
    }
    // display url string or message if there is no checked checkboxes
    if (counter > 0) {
        // remove first "&" from the generated url string
        url = url.substr(1);
        // display final url string
        alert(url);
        // or you can send checkbox values
        // window.location.href = 'my_page.php?' + url; 
    }
    else {
        alert('There is no checked checkbox');
    }
}

8 thoughts on “Sending checkbox values with JavaScript”

  1. Very good code snipet. Most important is generic in nature. Fulfilled my requirement perfectly. Thanks a lot.

  2. how do i make the list generated to appear on another page and printed out from a printer?

Leave a Comment