How can the selected option be highlighted in a multiple selection menu generated dynamically in PHP?
To highlight the selected option in a multiple selection menu generated dynamically in PHP, you can use the "selected" attribute in the HTML <option> tag. You need to check if the current option being generated matches the selected option and add the "selected" attribute accordingly.
<?php
// Sample array of options
$options = ['Option 1', 'Option 2', 'Option 3'];
// Selected option
$selectedOption = 'Option 2';
// Generate the select menu
echo '<select name="selectMenu" multiple>';
foreach ($options as $option) {
if ($option == $selectedOption) {
echo '<option value="' . $option . '" selected>' . $option . '</option>';
} else {
echo '<option value="' . $option . '">' . $option . '</option>';
}
}
echo '</select>';
?>
Related Questions
- What are the best practices for handling user input validation and processing in PHP to ensure data integrity and security?
- How can the error "FPDF error: Some data has already been output, can't send PDF file" be prevented when working with PDF files in PHP?
- What are common issues when embedding multiple webcams using PHP?