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
184 views
in Technique[技术] by (71.8m points)

php - How get value for unchecked checkbox in checkbox elements when form posted?

I have a form like below :

<form action="" method="post">
    <input type="checkbox" id="status_1" name="status_1" value="1" />
    <input type="checkbox" id="status_2" name="status_2" value="1" />
    <input type="checkbox" id="status_3" name="status_3" value="1" />
</form>

When i check all checkbox and post the form, the result is like this:

Array ([status_3] => 1 [status_2] => 1 [status_1] => 1 ) 

Then i uncheck second checkbox and post the form, the result is like this:

Array ( [status_3] => 1 [status_1] => 1 ) 

Is it possible to make result like this below when i uncheck second checkbox :

Array ( [status_3] => 1 [status_2] => 0 [status_1] => 1 ) 

There are ideas to do it?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

First way - hidden fields (disadvantage: the user can manipulate the value of the field (but one can manipulate the value of the checkbox too, so it's not really a problem, if you only expect 1 or 0))

<form action="" method="post">
<input type="hidden" name="status_1" value="0" />
<input type="checkbox" id="status_1" name="status_1" value="1" />
<input type="hidden" name="status_2" value="0" />
<input type="checkbox" id="status_2" name="status_2" value="1" />
<input type="hidden" name="status_3" value="0" />
<input type="checkbox" id="status_3" name="status_3" value="1" />
<input type="submit" />
</form>
<?php
var_dump($_POST);
/*
 * checking only the second box outputs:
 * 
 * array (size=3)
  'status_1' => string '0' (length=1)
  'status_2' => string '1' (length=1)
  'status_3' => string '0' (length=1)
 */

Second way - to assign default value for non-set indexes:

<form action="" method="post">
<input type="checkbox" id="status_1" name="status_1" value="1" />
<input type="checkbox" id="status_2" name="status_2" value="1" />
<input type="checkbox" id="status_3" name="status_3" value="1" />
<input type="submit" />
</form>
<?php
for($i = 1; $i<=count($_POST); $i++) {
    $_POST["status_$i"] = isset($_POST["status_$i"]) ? $_POST["status_$i"] : 0;
}
var_dump($_POST);

/**
 * Here we will be checking only the third checkbox:
 * 
 * array (size=3)
  'status_3' => string '1' (length=1)
  'status_1' => int 0
  'status_2' => int 0
 */

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

...