Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

PHP checkbox validation checked or not checked

I've been using similar code to this for my project and I'm able to get all of the "Checked" checkboxes using the $_POST[]. However, I also need to get the value of the unchecked checkboxes since this form is dynamically being built and the number of checkboxes may vary as well as change state from checked to unchecked and vice versa.

<form method='post' action=''> <tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
    </td> </tr> </table> <input type='submit' class='buttons'> </form>

<?php 
if (isset($_POST['checkboxvar'])) 
{
    print_r($_POST['checkboxvar']); 
}
?>

I've seen some suggestions using !isset($_POST[ ]) but I'm not certain on how that would work or if that is even a solution for the problem.

Any help would be appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I suggest using a javascript as suggested by other users.

If you want to use only PHP and HTML you can use the following solution. I write it, but I would not use this solution on a production environment.

<input type='hidden' name='checkboxvar[1]' value="0" />
<input type='checkbox' name='checkboxvar[1]' value='Option One' />1<br />
<input type='hidden' name='checkboxvar[2]' value="0" />
<input type='checkbox' name='checkboxvar[2]' value='Option Two' />2<br />
<input type='hidden' name='checkboxvar[3]' value="0" />
<input type='checkbox' name='checkboxvar[3]' value='Option Three' />3

In the $_POST array you should have something like that if Option One is selected.

Array
(
     [1] => Option One
     [2] => 0
     [3] => 0
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...