Process HTML checkboxes and their values

↘锁芯ラ 提交于 2020-01-01 19:27:48

问题


How can I process the checkboxes only if they're checked and grab the value of the checked ones only.

php

if (is_array($_POST['add'])) {
  foreach ($_POST['add'] as $key => $value) {
    $_POST['add'][$key] = mysql_real_escape_string(stripslashes($value));
  }
}

html

<input type="checkbox" id="wmeet_ce" 
        value="ce" 
        name="add[wmeet]" 
        title="Wanting To Meet" 
        class="checkbox {validate:{required:true,minlength:1}}"/>

<input type="checkbox" id="wmeet_sf"
        value="sf" 
        name="add[wmeet]" 
        class="checkbox"/>

<input type="checkbox" id="wmeet_sm" 
        value="sm" 
        name="add[wmeet]" 
        class="checkbox" />

回答1:


Only checked checkboxes are ever presented to PHP, so your PHP code is correct.

However, your HTML isn't correct, as all your checkboxes have the same name. This means PHP will only ever see one of them.

To get an array of checkboxes you either need to give your checkboxes unique names like this

<input type="checkbox" id="wmeet_ce" 
        value="ce" 
        name="add[ce]" 
        title="Wanting To Meet" 
        class="checkbox {validate:{required:true,minlength:1}}"/>

<input type="checkbox" id="wmeet_sf"
        value="sf" 
        name="add[sf]" 
        class="checkbox"/>

<input type="checkbox" id="wmeet_sm" 
        value="sm" 
        name="add[sm]" 
        class="checkbox" />

Or use the empty box technique like this.

<input type="checkbox" id="wmeet_ce" 
        value="ce" 
        name="add[]" 
        title="Wanting To Meet" 
        class="checkbox {validate:{required:true,minlength:1}}"/>

<input type="checkbox" id="wmeet_sf"
        value="sf" 
        name="add[]" 
        class="checkbox"/>

<input type="checkbox" id="wmeet_sm" 
        value="sm" 
        name="add[]" 
        class="checkbox" />


来源:https://stackoverflow.com/questions/8613250/process-html-checkboxes-and-their-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!