I am doing a PHP assignment where I am getting input that uses some checkboxes and stores the information in a file.
Let's say I have a checkbox
Active: <input type="checkbox" name="preference" value="Pepperoni" checked="checked>
When I say something like:
$Preference1 = $_POST['preference'];
What is stored in $Preference1
? Does it store information that tells whether the box was checked or not, or does it contain "Pepperoni"
? Is there a way to check to see if a box is checked? Like,
Pesudocode
if Preference1 is checked
add Pepperoni to the file;
if Preference2 is checked
add Sausage to the file;
I did work with radio buttons but those are a bit different since only one of those can be checked at a time, but for checkboxes, multiples boxes and be selected. Is there a way to see if a button is checked and if so, how would I do that? Thanks.
UPDATE After doing some digging around I found a post that did something like this:
$('#isAgeSelected').attr('checked')
But that is using jQuery. Would something like the .attr
work in PHP? Could I say something like
if($_POST['preference'].attr("checked"))
//do whatever
Does this work in PHP?
In this case you can try with store values into an single array. So you can track with multiple value that has been checked.
<?php
if(isset($_POST['submit']) && $_POST['submit']== 'submit'){
if(isset($_POST['preference']) && count($_POST['preference']>0)){
echo"<pre>";print_r($_POST['preference']);
} else {
echo "Empty";
}
}
?>
<form name='myForm' method='post'>
<input type="checkbox" name="preference[]" value="Pepperoni" >
<input type="checkbox" name="preference[]" value="Pepperoni1" >
<input type="checkbox" name="preference[]" value="Pepperoni2">
<input type='submit' name='submit' value='submit'>
</form>
Check this link. Something like:
if (isset($_POST['preference'])) {
// Checkbox is selected
} else {
// Alternate code
}
$Preference1 = $_POST['preference'] = "Pepperoni" //value from < input > tag
To check if box is checked, you have to check if $_POST['preference'] is set and is not NULL.
if (isset($_POST['preference'])) {
echo "Checkbox is selected";
}