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:
// function will loop through all input tags and create
// url string from checked checkboxes
function checkbox_test(){
var counter = 0; // counter for checked checkboxes
var i = 0; // loop variable
var url = ''; // final url string
// get a collection of objects with the specified 'input' TAGNAME
var 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's no checked checkbox");
}
Related posts
- JavaScript Drag and Drop example 4
- JavaScript Drag and Drop example 3
- JavaScript Drag and Drop example 2
- Maintain vertical scroll position
- JavaScript dialog box
Follow me on Twitter