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.
Edit option from Radio Buttons in PHP
Remove the lines of code below (or comment them out while you try it). Make a copy of the file before you make any changes in case you need to back out the attempt.
"trans_type", 'value'=>'pickup', 'required'=>true )); ?>
Dave 4862
More Answer
- How to send value attribute from radio button in PHP
- Radio Buttons with PHP Form Handling
- How to Get the multiple radio buttons values in PHP which having names dynamically
- pass selected option value from select to php
- Is there a config option in PHP to prevent undefined constants from being interpreted as strings?
- PHP mailer form with radio buttons using AJAX to send
- Php Javascript : Keeping radio buttons selected on page refresh
- PHP not receiving values for radio buttons
- Symfony2 : set default value from database in radio buttons choice form?
- How to validate dynamic radio button from PHP
- PHP Radio Buttons — Keep The Values in The Form after an Error
- Can’t $_POST values from disabled Radio buttons
- Dynamically creating Radio Buttons and Assigning selected Values PHP
- PHP/HTML/JavaScript — Creating buttons with data attributes from PHP to HTML/JavaScript
- Php retrieve a set of values from an unique SQL row and display it in an HTML option list
- How to pass data from radio buttons using jquery/AJAX
- Remove an option from a Zend Radio Form Element
- PHP Forms Radio Buttons
- Select an option from dropdown box using DOMCrawler in PHP
- Deleting an element from an array in PHP
- Returning JSON from a PHP Script
- How do I pass variables and data from PHP to JavaScript?
- Saving image from PHP URL
- Send email using the GMail SMTP server from a PHP page
- How to remove duplicate values from a multi-dimensional array in PHP
- How to include() all PHP files from a directory?
- PHP — how to best determine if the current invocation is from CLI or web server?
- How to fix error with xml2-config not found when installing PHP from sources?
- How to remove duplicate values from an array in PHP
- How to get the first item from an associative PHP array?
- Remove useless zero digits from decimals in PHP
- How can I execute PHP code from the command line?
- PHP function to build query string from array
- PHP — Extracting a property from an array of objects
- How do you reindex an array in PHP but with indexes starting from 1?
- How to call function of one php file from another php file and pass parameters to it?
- Sending email with PHP from an SMTP server
- Returning JSON from PHP to JavaScript?
- Using $_POST to get select option value from HTML
- Running a Python script from PHP
- how to get the cookies from a php curl into a variable
- How to create an array from a CSV file using PHP and the fgetcsv function
- Get data from JSON file with PHP
- Remove Trailing Slash From String PHP
- Redirecting from HTTP to HTTPS with PHP
- SilverStripe PHP Forms — If I nest a SelectionGroup inside a FieldGroup, one of the related SelectionGroup_Items’ Radio Box does not show up. Why?
- Use PHP to create, edit and delete crontab jobs?
- How to create and download a csv file from php script?
- Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
- Composer — the requested PHP extension mbstring is missing from your system
More answer with same ag
- Email sending not working in Mailgun to Outlook
- Expected response code 220 but got code «», with message «» in laravel 5.3
- cakephp validation on multiple dates
- Two way continuous socket communication
- php returns invalid json
- How to connect to apn with PHP using p8 auth key file
- PHP sorting multidimensional array, can only sort one column
- mysqli query issue. mysqli_real_escape_string error
- Detect encoding and make everything UTF-8
- Convert iteration number to a limited range (like day of week number)
- PHP: How to instantiate a class with arguments from within another class
- Laravel Eloquent orWhere Query
- PHP 7 regex not working the same way as in 5
- single folder or many folders for storing 8 million images of hundreds of stores?
- Using php Code in .html or .htm files
- Webbased chat in php without using database or file
- Reverse FILTER_SANITIZE_SPECIAL_CHARS with PHP
- PHP add elements to multidimensional array with array_push
- Accessing form input with HTML
- RestApi server code is not workinng
- how to not capture entire group with regex negative lookahead
- PHP/Magento — Variables within foreach not being updated properly
- Why use multiple PHP Exception classes
- Select One column Doctrine DQL
- «src/Entity/Order.php): failed to open stream: No such file or directory» — When make:entity — Symfony 5
- Cannot catch AWS S3 exception
- Sanitizing PHPSESSID
- Doctrine Exception: Deadlock found when trying to get lock
- passing a variable from php to bash
- Get last key-value pair in PHP array
- vcruntime140.dll 14.0 not compatible with PHP build
- Javascript function not responding when called inside PHP. (Trying to add items to option listbox)
- PHP — imagepng not working properly
- Using DateInterval to add weeks to a DateTime object
- Reset indexes to 1-based array
- PHP — Sort multi-dimensional array by another array
- What is the difference between extending a class and including it in PHP?
- Is there a way to store Arabic dates with Postgres?
- Get master request in Symfony 2.4
- PHP Security of login application
- PHPmailer and pdf attachment
- PHP CLI — Ask for User Input or Perform Action after a Period of Time
- Set width image in gridview yii2
- How can we restrict deactivated users via Auth::check in laravel 4.2
- Controller inheritance in Cake PHP?
- Setup and use parameters in PHPUnit data providers
- Gmail Oauth API get messages count
- Regex to escape double quotes inside double quotes with preg_replace
- Access @attributes data in SimpleXMLElement in PHP
- how to stop login button app asking for friends list permission