checkbox multiple select

Checkbox Multiple Select in HTML

If you want to allow the user to select multiple options from a list, you can use checkboxes. Here's an example:


<div>
  <p>Which colors do you like?</p>
  <ul>
    <li><input type="checkbox" name="colors" value="red">Red</li>
    <li><input type="checkbox" name="colors" value="green">Green</li>
    <li><input type="checkbox" name="colors" value="blue">Blue</li>
  </ul>
</div>

In this example, we have a list of colors with a checkbox next to each one. The "name" attribute is the same for all checkboxes, which means they belong to the same group. The "value" attribute specifies the value that will be sent to the server if the checkbox is checked.

When the form is submitted, you can use server-side code (such as PHP) to retrieve the values of the checked checkboxes. Here's an example:


$colors = $_POST['colors'];
foreach ($colors as $color) {
  echo $color . "<br>";
}

This code assumes that the checkboxes were submitted with the "POST" method and that their values were stored in an array called "colors". It then loops through the array and echoes each value.

Another way to handle multiple select options is using a "select" dropdown with the "multiple" attribute. Here's an example:


<div>
  <p>Which colors do you like?</p>
  <select name="colors[]" multiple>
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
  </select>
</div>

In this example, we have a "select" dropdown with the "multiple" attribute, which allows the user to select multiple options. The "name" attribute is set to "colors[]", which indicates that the selected values will be stored in an array called "colors".

When the form is submitted, you can use the same server-side code as before to retrieve the values of the selected options:


$colors = $_POST['colors'];
foreach ($colors as $color) {
  echo $color . "<br>";
}

Both methods accomplish the same thing, so it's up to you to decide which one to use based on your specific needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe