Forum Moderators: coopster

Message Too Old, No Replies

Problem With Checkboxes

Problem accessing checkbox results.

         

en_code

8:53 am on Jun 19, 2003 (gmt 0)

10+ Year Member



I have a page where I have some checkboxes. I want to be able to access the information retrieved by the checkboxes in a loop. I have inserted the checkboxes using this HTML:

[input type="checkbox" name="choiceX" value="yes"]

NOTE: X is a number that increments by 1 for each checkbox. So the first checkbox is called "choice1", the second is called "choice2" and so on.

So how do I take these checkbox variables (choice1, choice2, et cetera) and access a different one each time a loop runs? I want to run a loop which will get the value of each checkbox and - if the checkbox is ticked - will then add text to a list. I'm hoping for something that accomplishes this:

if (isset($choice1)) {
echo "Choice 1<br>"
}

if (isset($choice2)) {
echo "Choice 2<br>"
}

But accomplishes it via a loop so that the "if" statement is written once and the "if" statement tests a different variable each time. Any ideas? Sorry if this message is a bit incoherent, just let me know and I'll try to explain some more.

Nick_W

8:58 am on Jun 19, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi, and welcome to WebmasterWorld

I think you're better off putting these values in an array like this:

name="choice[]" value="whatever"

then running over it like this


foreach($choice as $key => $val) {
if(isset($key)) {
print($val."<br />\n");
}

Nick

en_code

9:07 am on Jun 19, 2003 (gmt 0)

10+ Year Member



Hey, thanks a lot, you've fixed my problem! :)

I can't believe it was so easily fixed. Sorry, I only started learning PHP last night, so I'm a big phat noob.

jatar_k

3:41 pm on Jun 19, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Nick's answer is the straightforward way but you can still do it the other way

5 checkboxes


$counter = 1;
while ($counter <= 5) {
if(isset(${"choice" . $counter}))
echo ${"choice" . $counter} . "<br />\n";
$counter++;
}

and
Welcome to WebmasterWorld