Get POST data from multiple checkboxes?

前端 未结 3 1666
时光取名叫无心
时光取名叫无心 2020-12-06 16:40

Im trying to create a form using PHP and I cant seem to find a tutorial on what I need so thought Id ask on here.

I have a multiple checkbox option on my page...

相关标签:
3条回答
  • 2020-12-06 17:05
    <input type="checkbox" value="Other" name="service">Other<input type="hidden" value="Other" name="service"></span>
    

    You've got a hidden input field with the same name as the checkbox. "later" fields with the same name as an earlier one will overwrite the previous field's values. This means that your form, as posted above, will ALWAYS submit service=Other.

    Given the phrasing of your question in the html, it sounds more like you'd want a radio button, which allows only ONE of a group of same-name fields to be selected. Checkboxes are an "AND" situation, radio buttons correspond to "OR"

    0 讨论(0)
  • 2020-12-06 17:15

    Currently it's just catching your last hidden input. Why do you have that hidden input there at all? If you want to gather information if the "Other" box is checked, then you have to hide the

    <input type="text" name="other" style="display:none;"/> 
    

    and you can show it with javascript when the "Other" box is checked. Something like that.

    Just make the name attribute service[]

    <li>
    <label>What service are you enquiring about?</label>
    <input type="checkbox" value="Static guarding" name="service[]">Static guarding<br />
    <input type="checkbox" value="Mobile Patrols" name="service[]">Mobile Patrols<br />
    <input type="checkbox" value="Alarm response escorting" name="service[]">Alarm response escorting<br />
    <input type="checkbox" value="Alarm response/ Keyholding" name="service[]">Alarm response/ Keyholding<br />
    <input type="checkbox" value="Other" name="service[]">Other</span>
    </li>
    

    Then in your PHP you can access it like so

    $service = $_POST['service'];
    echo $service[0]; // Output will be the value of the first selected checkbox
    echo $service[1]; // Output will be the value of the second selected checkbox
    print_r($service); //Output will be an array of values of the selected checkboxes
    

    etc...

    0 讨论(0)
  • 2020-12-06 17:16

    Name the fields like service[] instead of service, then you'll be able to access it as array. After that, you can apply regular functions to arrays:

    • Check if a certain value was selected:

       if (in_array("Other", $_POST['service'])) { /* Other was selected */}
      
    • Get a single newline-separated string with all selected options:

       echo implode("\n", $_POST['service']);
      
    • Loop through all selected checkboxes:

       foreach ($_POST['service'] as $service) {
           echo "You selected: $service <br>";
       }
      
    0 讨论(0)
提交回复
热议问题