JavaScript Loop Checkbox Array

Looping through an array of elements

A list of records in a form required two tick boxes, each an array holding the id of the record. Only one box should be ticked:

checkboxes
checkboxes

he HTML of the Check boxes:

input type=”checkbox” value=”22″ onchange=”reject_check(22)” name=”confreject_ids[]” id=”confreject_ids_”

input type=”checkbox” value=”22″ onchange=”accept_check(22)” name=”confaccept_ids[]” id=”confaccept_ids_”

  • On clicking a check box the function is called and the ID of the record passed, so if an accept checkbox is pressed then thereject_check(id) function is called.
  • The script sets a variable to the array of checkboxes
  • Sets a variable to the number of checkboxes
  • Loops through the check boxes and checks the value it holds.
  • If the value equals what was passed through to the function then it is the check box belonging to that record and it is unchecked.
function accept_check(id) {
	var checkboxes = document.getElementsByName('confreject_ids[]');
    var cboxLength = checkboxes.length;    

 	for ( i=0; i < cboxLength; i++ ) { 
    	if (checkboxes[i].value == id) {
			checkboxes[i].checked = false;  
		}
    }
}   

function reject_check(id) {
	var checkboxes = document.getElementsByName('confaccept_ids[]');
    var cboxLength = checkboxes.length;    

 	for ( i=0; i < cboxLength; i++ ) { 
    	if (checkboxes[i].value == id) {
			checkboxes[i].checked = false;  
		}
    }
}

Leave a Reply

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