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

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
            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
        // or you can send checkbox values
        // window.location.href = 'my_page.php?' + url; 
    else {
        alert('There is no checked checkbox');

This entry was posted on January 9, 2009 and is filed under JavaScript

Related posts

8 Responses to Sending checkbox values with JavaScript

  1. Sunil says:

    Thanks Very much, It's very usefull in our project.

  2. Girish says:

    Thanks alot man. this sample code met my requirement perfectly.

  3. Kaushik says:

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

  4. Simple, but it run well.. nice snippet.. i like it.

  5. R.Vasanthi says:

    i try this. its helped me.
    thanks a lot.

  6. Deepan.A says:

    Thanks a lot, I am using it for my project

  7. dbunic says:

    Thank all of you for giving me feedback info.

  8. Sam says:

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

Leave a Reply

Your email address will not be published. Required fields are marked *


In case of posting HTML tags or JavaScript code please convert special characters to HTML entities.
Especially pay attention to convert "<" character to "&lt;" entity!