Passing checkbox state to PHP

前端 未结 6 1584
南笙
南笙 2021-01-24 22:54


This works fine, ho

相关标签:
6条回答
  • 2021-01-24 23:32

    Everything is working normal with your code so far.

    I'm assuming you are creating the hidden field so that 0 is passed to the server when the checkbox is not checked. The problem is that they both get passed when the check box is checked.

    As Death said, the way you should be doing it is with a single checkbox and then checking if the value has been sent to the server or not. That's just how checkboxes work.

    If you want to have a default set then you will have to handle all that on the server side based on weather the checkbox has a value.

    For example:

    $myValue = "";
    if(isset($_POST['check_box_1']))
    {
        $myValue=$_POST['check_box_1'];
    }
    else
    {
        $myValue="0";
    }
    
    0 讨论(0)
  • 2021-01-24 23:36

    You shouldn't need the hidden field. You should in fact not trust any of the form fields sent in the first place. What this means is that you cannot make code which takes the sent fields and trust them to send the correct data (which I assume you do now).

    What you should do is to handle all fields you expect to get. That way if you don't get the checkbox value you can still handle that as if it was unticked. Then you also get the added inherent feature of throwing away form data you don't expect in the first place.

    0 讨论(0)
  • 2021-01-24 23:37

    That's normal.

    They must be both type="checkbox" to pass only 1 value.

    If you want to get only 1 in any cases you can do:

    <input type="checkbox" style="display:none;" name="check_box_1" value="0">
    
    0 讨论(0)
  • 2021-01-24 23:38

    Make sure the first input field is of type Checkbox, or else it won't behave like one.

    <input type="checkbox" name="check_box_0" value="0" />
    <input type="checkbox" name="check_box_1" value="1" />
    
    0 讨论(0)
  • 2021-01-24 23:45

    No, it will pass all the form data, whatever it is. The right way to do this is not to set the checkbox via a hidden field but to set the checkbox with whatever its state actually is!

    I mean... why are you adding the hidden field to begin with?

    Your PHP is receiving two fields named check_box_1, and last time I checked there was no way to guarantee that the params would get read into the REQUEST hash in the exact same order as you sent them, so, there's no way to tell which one will arrive last (that's the one whose value will get set). So... this is not the right approach to whatever problem you're trying to solve here.

    Welcome to Stack, btw! If you find answers useful or helpful, make sure to mark them as correct and vote them up.

    0 讨论(0)
  • 2021-01-24 23:46

    The better approach is to remove the hidden field, and simply have a check in PHP:

    if ($_POST['check_box_1']=='1') { /*Do something for ticked*/ }
    else { /*Do something for unticked*/ }
    
    0 讨论(0)
提交回复
热议问题