- PHP Select Option
- A quick introduction to the element
- Getting the selected value from a element
- Select with multiple options
- Summary
- Manipulation of HTML Select Element with Javascript
- Important Properties and Methods of Select Element
- Important Properties of Option Element
- Setting Value of Select Element
- Getting the Value and Text/Label of the Selected Options
- Adding an Option
- Deleting an Option
- How to Get Multiple Selected Values of the Select Box in PHP
- Using the Multiple Attribute of HTML
PHP Select Option
Summary: in this tutorial, you will learn how to use the element to create a drop-down list and a list box and how to get the selected values from the element in PHP.
A quick introduction to the element
The is an HTML element that provides a list of options. The following shows how to define a element in HTML:
label for="color">
Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)
The element has two important attributes:
- id – the id associates the element with a element
- name – the name attribute associates with the value for a form submission.
The element nested inside the element defines an option in the menu. Each option has a value attribute. The value attribute stores data submitted to the server when it is selected.
If an option doesn’t have the value attribute, the value attribute defaults to the text inside the element.
To select an option when the page loads for the first time, you can add the selected attribute to the element.
The following example selects the Green option when the page first loads:
label for="color">
Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)
Getting the selected value from a element
We’ll create a form that uses a element.
First, create the following folders and files:
├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.php
Code language: JavaScript (javascript)
Second, place the following code in the header.php file:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> link rel="stylesheet" href="css/style.css"> title>PHP select option title> head> body class="center"> main>Code language: HTML, XML (xml)
Third, place the following code in the footer.php file:
main
> body> html>Code language: HTML, XML (xml)
Fourth, add the following code to the get.php file to create a form that has one element with a submit button:
form action="" method="post">
div> label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select> div> div> button type="submit">Select button> div> form>Code language: HTML, XML (xml)
The form uses the POST method to submit data to the webserver.
Finally, add the following code to the post.php file:
$color = filter_input(INPUT_POST, 'color', FILTER_SANITIZE_STRING); ?> if ($color) : ?> p>You selected span style="color:"> echo $color ?> span>
p> p>a href="index.php">Back to the form a> p> else : ?> p>You did not select any color p> endif ?>Code language: HTML, XML (xml)
To get the selected value of the element, you use the $_POST superglobal variable if the form method is POST and $_GET if the form method is GET .
Alternatively, you can use the filter_input() function to sanitize the selected value.
If you select the first option of the element, the selected value will be empty. Otherwise, the selected value is red, green, or blue.
Select with multiple options
To enable multiple selections, you add the multiple attribute to the element:
select name="colors[]" id="colors" multiple>
. select>Code language: HTML, XML (xml)
When you select multiple options of a element and submit the form, the name will contain multiple values rather than a single value. To get multiple selected values, you add the square brackets ( []) after the name of element.
Let’s take a look at an example of using a element with multiple selections.
First, create the following folders and files:
. ├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.php
Code language: JavaScript (javascript)
Second, place the following code into the header.php file:
html>
html lang="en"> head> meta charset="UTF-8" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> title>PHP Listbox title> link rel="stylesheet" href="css/style.css"> head> body class="center"> main>Code language: HTML, XML (xml)
Third, add the following code to the footer.php file:
main
> body> html>Code language: HTML, XML (xml)
Fourth, include the header.php and footer.php files in the index.php :
require __DIR__ . '/inc/header.php'; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') < require __DIR__ . '/inc/get.php'; > elseif ($request_method === 'POST') < require __DIR__ . '/inc/post.php'; > require __DIR__ . '/inc/footer.php';
Code language: HTML, XML (xml)
If the HTTP request is GET, the index.php file will show a form from the get.php file. When the form is submitted, the post.php file will handle the form submission.
Fifth, create a form that contains a element with the multiple attribute in the get.php file. The name of the element has an opening and closing square bracket [] so that PHP can create an array that holds the select values.
form action="" method="post">
div> label for="colors">Background Color: label> select name="colors[]" id="colors" multiple> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> option value="purple">Purple option> option value="magenta">Magenta option> option value="cyan">Cyan option> select> div> div> button type="submit">Submit button> div> form>Code language: HTML, XML (xml)
Finally, handle the form submission in the post.php file:
$selected_colors = filter_input( INPUT_POST, 'colors', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY ); ?> if ($selected_colors) : ?> p>You selected the following colors: p>
ul> foreach ($selected_colors as $color) : ?> li style="color:"> echo $color ?> li> endforeach ?> ul> p> p> else : ?> p>You did not select any color. p> endif ?> a href="index.php">Back to the form a>Code language: HTML, XML (xml)
The post.php file uses the filter_input() function to get the selected colors as an array. If you select one or more colors, the post.php file will display them.
Summary
- Use the element to create a dropdown list.
- Use the multiple attribute to create a list that allows multiple selections.
- Use $_POST to get the selected value of the select element if the form method is POST (or $_GET if the form method is GET ).
- Add square brackets( [] ) after the name of the element to get multiple selected values.
Manipulation of HTML Select Element with Javascript
Manipulation of the element with Javascript is quite commonly required in web applications. This tutorial explains how you can perform common operations on select element with vanilla Javascript — adding/deleting options or getting/setting the selected options.
Important Properties and Methods of Select Element
- value : It gives the value of the first selected option (a multi-valued select may have multiple selected options)
- options : It gives the list of all option elements in the select
- selectedOptions : It gives the list of option elements that are currently selected
- selectedIndex : It is an integer that gives the index of first selected option. In case no option is selected, it gives -1
- add() : This method adds a new option to the list of options
- remove() : This method removes an option from the select element
Important Properties of Option Element
- value : It gives the value of the option
- text : It gives the text inside the option
- selected : It tells whether the option is selected or not
Setting Value of Select Element
For a single valued select, setting its value can be done with the value or the selectedIndex property.
// Set option with value 'Orange' as selected document.querySelector('#choose-fruit').value = 'Orange'; // Set the option with index 2 as selected => Sets the 'Banana' option as selected document.querySelector('#choose-fruit').selectedIndex = 2;
For a multiple valued select, setting multiple selected options can be done by setting the selected attribute of the required option.
// choose the first option document.querySelector('#choose-fruit-multiple').options[0].selected = true; // also choose the third option document.querySelector('#choose-fruit-multiple').options[2].selected = true;
This will obviously work for single valued select also, but using the value property is much direct for them.
Getting the Value and Text/Label of the Selected Options
The selectedOptions property of the select element gives the list of options that are currently selected. Each element in this list is a DOM element — so you can use the value and text property to get the value and inside text of the option.
// For a normal select (and not multi-select) the list would contain only a single element var text = document.querySelector('#choose-fruit').selectedOptions[0].text; var value = document.querySelector('#choose-fruit').selectedOptions[0].value;
For a multiple select element, you can loop over the list to get all selected options.
var selected_options = document.querySelector('#choose-fruit-multiple').selectedOptions; for(var i=0; i // output Orange 2 Grapes 5
Adding an Option
The add method can be used to add a new option in the select. You can also specify the exact positon where the option needs to be inserted.
var option = document.createElement('option'); option.text = 'BMW'; // append option at the end // new options will be Volvo, Audi, Mercedes & BMW document.querySelector('#choose-car').add(option, null);
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 0 // new options will be BMW, Volvo, Audi & Mercedes document.querySelector('#choose-car').add(option, 0);
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 2 // new options will be Volvo, Audi, BMW & Mercedes document.querySelector('#choose-car').add(option, 2);
Deleting an Option
The remove method can be used to delete an option at a specified index.
// remove the option at index 1 // new options will be Volvo & Mercedes document.querySelector('#choose-car').remove(1);
How to Get Multiple Selected Values of the Select Box in PHP
The task of this tutorial is retrieving the multiple selected values of the selected box in PHP.
Go ahead to see the solution.
Using the Multiple Attribute of HTML
To meet the goal, you can use the multiple attribute of HTML.
Selecting multiple values of HTML replies upon the browser and the operating system.
So, below we demonstrate the actions to take:
- On windows, you should hold down + CTRL key for selecting the multiple option.
- On Mac, it is necessary to hold down the command key for selecting the multiple option.
An example of creating a list of items with HTML looks like this:
html> html> head> title>Title of the document title> head> body> form method="post" action="/form/submit"> h4>SELECT SUJECTS h4> select name="subject" multiple size="6"> option value="english">ENGLISH option> option value="maths">MATHS option> option value="computer">COMPUTER option> option value="chemistry">CHEMISTRY option> option value="geography">GEOGRAPHY option> option value="italian">ITALIAN option> select> input type="submit" name="submit" value="Submit" /> form> body> html>
Now, let’s get to retrieving the multiple selected values from the list. You are required to use the form method and loop for getting the selected value:
html> html> head> title>Title of the document title> head> body> form method="post" action="/form/submit"> h4>SELECT SUJECTS h4> select name="subject[]" multiple size="6"> option value="english">ENGLISH option> option value="maths">MATHS option> option value="computer">COMPUTER option> option value="chemistry">CHEMISTRY option> option value="geography">GEOGRAPHY option> option value="italian">ITALIAN option> select> input type="submit" name="submit" value="Submit" /> form> body> html> "; > else echo "Select an option first !!"; > ?>
So, in this snippet, we represented a handy method of getting multiple selected values of the selected box in PHP.