简体   繁体   中英

Checkbox and Hidden both passing value even if checkbox is checked or not

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.

With a modification to the PHP to make it valid (move hidden input to same table cell) you might try some simple javascript to disable the hidden value ( which should remove it from the POST array )

echo "<td>
    <input type='hidden' name='cash[]' value='Non Cash' />
    <input type='checkbox' name = 'cash[]' value='Cash'/>
</td>";

And the Javascript

<script>
    document.querySelectorAll('input[type="checkbox"][name="cash[]"]').forEach( input=>{
        input.addEventListener('click',function(e){
            this.previousElementSibling.disabled=this.checked;
        });
    })
</script>

I have not tested the above - please excuse possible mistooks.

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>"; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM