Page 1 of 1

How to specify a set of checkboxes and recheck them

Posted: Tue Apr 20, 2010 1:21 am
by siko
I am trying to recheck checkboxes and reselect radio buttons and drop down lists on the current page, using values from a previous page.

Say I have a set of check boxes:

(checked) Psychology
(checked) Introduction to Mathematical Studies
(unchecked) Introduction to Java Language
(checked) Database Systems

And I click a button 'Next', which passes all these values to the next page by $_GET.

On the next page, I have the exact same set of checkboxes, and I want to use these values to recheck the checkboxes.

I wrote some code here, which works, but problem is it is in javascript and not ideal because if the user has js turned off it wouldnt work.

Code: Select all

for (var subject_count = 0; subject_count < subject.length; subject_count++) {
	var inputs = document.getElementsByTagName ('input');
	if (inputs) {
		for (var i = 0; i < inputs.length; ++i) {
			if (inputs[i].type == 'checkbox' && inputs[i].name == 'my_subject[]') {
				if (inputs[i].value == subject[subject_count])
					inputs[i].checked = true;
			}
		}
	}
}
In the above code, I specify the exact checkbox by selecting inputs.type, inputs.name, and inputs.value, a combination of these 3 will specify a unique checkbox. This is because for my checkboxes, the attributes are:

Code: Select all

<input type="checkbox" name="my_subject[]" value="801"/> blah...
<input type="checkbox" name="my_subject[]" value="802"/> blah blah..
The checkboxes are an array.

My question is, how do I specify a checkbox like that in php? Or what can I do alternatively?

Re: How to specify a set of checkboxes and recheck them

Posted: Tue Apr 20, 2010 3:52 am
by requinix
What PHP will receive is a list of checked checkboxes. You will not get the unchecked ones.

Sort them in the same order you have them printed, then loop over both lists (the master list and the checked list) at the same time.

Code: Select all

sort(masterlist)
sort(checkedlist)

m = first(masterlist)
c = first(checkedlist)
while not end of masterlist
	if m == c then
		checked = true
		c = next(checkedlist)
	else
		checked = false
	end if

	print checkbox

	m = next(masterlist)
end while

Re: How to specify a set of checkboxes and recheck them

Posted: Tue Apr 20, 2010 10:19 am
by siko
Thanks for the reply tasairis.

I'm new to web programming so pardon me if I am asking something stupid..

If I use PHP to do this, does it mean I have to print out the html for the checkboxes using PHP as well? Correct me if I am wrong, I understand all the PHP code on the page gets run first on page load.

I.e. Can I have this typed out in my html code, and then use PHP to modify them?

<input type="checkbox" name="my_subject[]" value="801"/> blah...
<input type="checkbox" name="my_subject[]" value="802"/> blah blah..

Problem is because I need to type the corresponding subject next to its checkbox, which makes it non loopable..