Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selected value of HTML select box with PHP

Tags:

html

php

I have a next piece of the template:

<select name="interest">
    <option value="seo">SEO и Блоговодство</option>
    <option value="auto">Авто</option>
    <option value="business">Бизнес</option>
    <option value="design">Дизайн</option>
    ...

and store resulting value in $result['interest'].

How can I mark option element as selected with PHP?

Thanks!

like image 881
akrisanov Avatar asked Sep 19 '10 19:09

akrisanov


People also ask

How can we get the value of selected option in a select box using PHP?

PHP 8 Get Single Selected Values of Select Box php if(isset($_POST['submit'])){ if(! empty($_POST['Fruit'])) { $selected = $_POST['Fruit']; echo 'You have chosen: ' . $selected; } else { echo 'Please select the value. '; } } ?>

How do you get the selected value of dropdown in PHP with submit?

To get value of a selected option from select tag:php if(isset($_POST['submit'])){ $selected_val = $_POST['Color']; // Storing Selected Value In Variable echo "You have selected :" .

How do you set the value of a select tag?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

How do you have an HTML input field appear when the value other is selected with PHP?

it needs to go into a script tag (i.e. <script>... </script> ) so in PHP you could add that to an echo statement - e.g. echo "<script type=\"text/javascript">var...


2 Answers

The manual way.....

<select name="interest">
    <option value="seo"<?php if($result['interest'] == 'seo'): ?> selected="selected"<?php endif; ?>>SEO и Блоговодство</option>
    .....

The better way would be to loop through the interests

$interests = array(
    'seo' => 'SEO и Блоговодство',
    'auto' => 'Авто',
    ....
);

<select name="interest">
<?php foreach( $interests as $var => $interest ): ?>
<option value="<?php echo $var ?>"<?php if( $var == $result['interest'] ): ?> selected="selected"<?php endif; ?>><?php echo $interest ?></option>
<?php endforeach; ?>
</select>
like image 200
Galen Avatar answered Oct 13 '22 09:10

Galen


<?php
$interests = array('seo' => 'SEO и Блоговодство',  'auto' => 'Aвто', 'business' => 'Бизнес', ...);
?>
<select name="interest">
<?php
foreach($interests as $k => $v) {
?>
   <option value="<?php echo $k; ?>" <?php if($k == $result['interest']) ?> selected="selected" <?php } ?>><?php echo $v;?></option>
<?php
}
?>
</select>
like image 25
Jacob Relkin Avatar answered Oct 13 '22 09:10

Jacob Relkin