Reputation: 21
I have many checkboxes like this one:
<input type="checkbox" name="isGood[]">
For example, I have 6 checkboxes and then I checked 3 of them. When I submit it, print_r($_POST)
returns only this:
Array
(
isGood => array(
[0] => on
[1] => on
[2] => on
)
)
And the other 3 values are undefined. What am I doing wrong?
Upvotes: 0
Views: 686
Reputation: 502
Use array index in html for checkboxes, like:
<input type="checkbox" name="isGood[1]">
<input type="checkbox" name="isGood[2]">
<input type="checkbox" name="isGood[3]">
Use following to check checkbox in php:
$isGood = $_POST['isGood'];
if ($isGood) {
if (isset($isGood[1])) {...}
if (isset($isGood[2])) {...}
if (isset($isGood[3])) {...}
}
Update: fix code syntax
Upvotes: 1
Reputation: 1291
Okay, so I ran some tests and since I can't tell exactly how your entire code looks like, nor if you're using AJAX (which I would prefer), I created this simple code that can guide you on one way to do it, although not the best at all in my opinion. The idea of this code is to send the isGood
-named hidden input's value to the same page and output the generated array from that stringified JSON object. This object is needed because, as above commented, what you want can't be done the way you wanted because it's not how it works. The json_decode()
function creates the array in PHP.
<?php
if(isset($_POST['isGood'])){
echo '<pre>';
print_r(json_decode($_POST['isGood'], true));
echo '</pre>';
}
?>
<script type="application/javascript">
// this function must be at the end of the file before closing the <body> tag
function updateIsGoodValues(){
let checkboxes = document.getElementsByName('isGoodValues'),
isGood = Array();
checkboxes.forEach(function(e, i, a){
if(e.checked){
isGood.push('on');
} else {
isGood.push('off');
}
});
document.getElementById('isGoodResults').value = JSON.stringify(isGood);
}
updateIsGoodValues(); // makes 'off' the default value
</script>
<form method="post" action="">
<input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
<input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
<input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
<input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
<input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
<input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
<input type="hidden" id="isGoodResults" name="isGood">
<button>Send</button>
</form>
The result will be something like this (if the first, third, and fifth checkboxes are checked):
Array
(
[0] => on
[1] => off
[2] => on
[3] => off
[4] => on
[5] => off
)
Upvotes: 1