Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k 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 Reply

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
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...