I have a following code which I am using to pass value from check box.
echo "<input type='hidden' name='cash[]' value='Non Cash' />";
echo "<td><input type= 'checkbox' name = 'cash[]' value='Cash'/></td>";
But when I submit the form, value from hidden type pass through even if I check checkbox or no. For example, if I check checkbox like below, cash array will contains value from hidden type as well from checked checkbox too.
image of checked checkbox in a html form
array showing data from both hidden and checkbox
So, is there anyway I can avoid value from hidden type if checkbox is checked in cash array?
Thank you very much is advance.
When you use []
it dynamically creates a new array element. You need to pair them up with the same index. In this way, with the checkbox coming second it will overwrite the hidden input if it is checked:
echo "<input type='hidden' name='cash[0]' value='Non Cash' />";
echo "<td><input type='checkbox' name='cash[0]' value='Cash'/></td>";
echo "<input type='hidden' name='cash[1]' value='Something' />";
echo "<td><input type='checkbox' name='cash[1]' value='Something Else'/></td>";
The way you do it now with []
will result in the hidden input $_POST['cash'][0]
AND the checkbox $_POST['cash'][1]
. If you don't need multiple checkboxes with the same name, then don't use an array at all:
echo "<input type='hidden' name='cash' value='Non Cash' />";
echo "<td><input type='checkbox' name='cash' value='Cash'/></td>";