1
0

More than 1 year has passed since last update.

なに? チェックボックスオフでも確実にPOSTする方法があるやと?

Last updated at Posted at 2022-09-11

ある日の業務中

ぐっちー
「checkboxってオフの時postされんからオフの処理いちいち書くのめんどくさいな~」
先輩
「それならええ方法があるがな」

ぐっちー
「ほんまですか? 教えてください!」
先輩先輩
「1回しか言わんから永久保存版な」

ぐっちー
「了解です!」

一般的な書き方

index.html
<input type="checkbox" id="hoge" name="hoge" value="1">
<label for="hoge">チェックオン</label>
index.php
$in = $_POST

//初期化
$hoge = 0;
if(isset($in['hoge'])){
    $hoge = intval($in['hoge']);
}else{
    $in['hoge'] = $hoge;
}

$list = array();
$list = search_list($in); //DBからリストを取得する関数の想定

先輩の書き方

index.html
<input type="hidden" name="hoge" value="0">
<input type="checkbox" id="hoge" name="hoge" value="1">
<label for="hoge">チェックオン</label>
index.php
$in = $_POST

//初期化
$hoge = 0;

//あるとわかっていてもissetしたほうがよい
if(isset($in['hoge'])){
    $hoge = intval($in['hoge']);
}


$list = array();
$list = search_list($in); //DBからリストを取得する関数の想定

先輩
「チェックボックスの前にhiddenで埋め込むんよ」

ぐっちー
「なるほど チェックボックスがオフの場合は、hiddenのvalueがpostされるんですね!」
先輩
「そうや、でも絶対チェックボックスの前に書かんといけんからな?」

ぐっちー
「後ろに書いたらチェックボックスがオンだろうがオフだろうがhiddenのvalueがpostされるからですね!」
先輩
「そういうことや!」
「あと、nameも同じにすることを忘れるなよ」

ぐっちー
「了解しました!」

まとめ

ちょっとしたことでコード記載量を減らせて便利!

最後まで読んでいただきありがとうございました!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0