tesfa koli
tesfa koli

Reputation: 755

Selecting check boxes

I don't know how to do the following and would like some help. I have a php file which opens and displays some details in an array from a .txt file, with check boxes to be selected. Once the user selects those check boxes and clicks go, I need another php file which identifies selected check boxes and displays the data.

EDIT: You are forgetting the details, the check boxes will be associated with are in an array, so when the user enters a search term only the relevant info will pop up along with the check box. This means all check boxes have same id and are the same. How do I fix this?

Upvotes: 0

Views: 137

Answers (3)

kingmaple
kingmaple

Reputation: 4320

Check box is:

<input type="checkbox" name="checkbox-name" value="1"/>

If this checkbox is checked and this form is submitted, then on the target page the checkbox is:

$_POST['checkbox-name']=1;

If the checkbox was not defined, then the POST value is not set, for example:

if(!isset($_POST['checkbox-name'])){ echo 'not selected'; }

EDIT:

If arrays are needed, then the names of all the checkbox'es of the same array should be like:

<input type="checkbox" name="my-checkboxes[]" value="first"/>

Then this can be looped through in PHP by:

foreach($_POST['my-checkboxes'] as $values){
    echo $values;
}

Same applies to other HTML form elements that can be sent as an array.

Upvotes: 2

ajmint
ajmint

Reputation: 11

Assuming your initial page has this:

<form action="results.php" method="POST">

<input type="checkbox" name="checkbox1" value="1" />
<input type="checkbox" name="checkbox2" value="2" />
<input type="checkbox" name="checkbox3" value="3" />
<input type="submit" value="Submit" />

</form>

Your results.php should be something like:

<?php

echo isset($_POST['checkbox1']) ? "Box 1 is selected.<br />" : "Box 1 is not selected.<br />";
echo isset($_POST['checkbox2']) ? "Box 2 is selected.<br />" : "Box 2 is not selected.<br />";
echo isset($_POST['checkbox3']) ? "Box 3 is selected." : "Box 3 is not selected.";

?>

EDIT: You could also stick them into variables, like this:

$cb1 = isset($_POST['checkbox1']) ? true : false;
$cb2 = isset($_POST['checkbox2']) ? true : false;
$cb3 = isset($_POST['checkbox3']) ? true : false;

And do some if statements:

if (!$cb1 && $cb2 && $cb3) {
    echo "Option 1 is pretty much essential, or your gerbil 
    could escape within the first few hours of ownership.";
} else if ($cb1 && $cb2 && !$cb3) {
    echo "If you don't get him a water bottle, he may turn vicious.";
} else if (!$cb1 && !$cb2 && !$cb3) {
    echo "Right, that's it, we're calling the RSPCA!";
}

And so on…

Upvotes: 1

adis
adis

Reputation: 5951

These checkboxes are presented as HTML, I suppose. If that is the case you can use jQuery:

$("input:checkbox[name=type]:checked").each(function()
{
 // do your stuff here
});

Upvotes: 0

Related Questions