Scenario: You want to create for instance a quiz or survey. You have x number of checkoxes in your HMTL form with alternative answers to the questions. You have different values to this checkboxes, like e.g. the database id that you need to save the users answer in the db. You could of course create a loop and track which id the checkbox is connected to, but it is most often safer to store the id in the checkbox value property.
Problem:
- You do not know how many checkboxes which will be created in a e.g. PHP for-loop with data selected from a database.
- There can be other form elements as well, you have to filter them out.
- You do not know the name of the checkboxes so you can not access them with eg. form.checkoxname.value; .
- You do not know the id, you can not use document.etElementById(‘id’), or it is complicated to get the number of checkboxes without using JQuery’s .serialize(); getElementsById()
- You do not want to use JQuery for this single function if you are not going to use JQuery for other tasks on your siite.
Solution: Use elements.length. As in form.elements.length or document.elements.length. Use the “type” property to check if it is a checkbox or another form element, like this:
function checkCheckBoxes( form ){
console.log(form.elements.length);
for(i=0; i<form.elements.length; i++){
if(form.elements[i].type == "checkbox") console.log("checkbox");
if(form.elements[i].type == "checkbox"){
if(form.elements[i].checked){
return true;
}
}
}
alert("You have to select at least one checkbox!");
return false;
}
In my case I have 1 text input tag, 1 hidden input tag, and 3 textboxes. This piece of code will therefore output this in the JavaScript console:
5checkboxcheckboxcheckbox
Where 5 is the length and it verifies that it is three checkboxes in the if() test inside the for loop, and set the for-loop to loop at form.elements.length;, We can use the same if() test to filter all other elements than the checkboxes. So the final code will look like this:
function checkCheckBoxes( form ){
for(i=0; i<form.elements.length; i++)
if(form.elements[i].type == "checkbox" && form.elements[i].checked)
return true;
alert("LYou must select at least one alternative!");
return false;
}
