Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html select option SELECTED

I have in my php

$sel = "
    <option> one </option>
    <option> two </option>
    <option> thre </option>
    <option> four </option>
";

let say I have an inline URL = site.php?sel=one

if I didn't saved those options in a variable, I can do it this way to make one of the option be SELECTED where value is equal to $_GET[sel]

<option <?php if($_GET[sel] == 'one') echo"selected"; ?> > one </option>
<option <?php if($_GET[sel] == 'two') echo"selected"; ?> > two </option>
<option <?php if($_GET[sel] == 'three') echo"selected"; ?> > three </option>
<option <?php if($_GET[sel] == 'four') echo"selected"; ?> > four </option>

but the problem is, I need to save those options in a variable because I have a lot of options and I need to call that variable many times.

Is there a way to make that option be selected where value = $_GET[sel] ?

like image 631
Samsan Phone Number Lookup Avatar asked Oct 08 '12 13:10

Samsan Phone Number Lookup


People also ask

How do you keep selected option in HTML?

The selected attribute is a boolean attribute. When present, it specifies that an option should be pre-selected when the page loads. The pre-selected option will be displayed first in the drop-down list. Tip: The selected attribute can also be set after the page loads, with a JavaScript.

How do you select multiple options in HTML?

For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.


2 Answers

This is simple example by using ternary operator to set selected=selected

<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $key => $value) { ?>
  <option value="<?php echo $key;?>" <?php echo ($key ==  '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
like image 112
Muhammad Fahad Avatar answered Sep 23 '22 12:09

Muhammad Fahad


Just use the array of options, to see, which option is currently selected.

$options = array( 'one', 'two', 'three' );

$output = '';
for( $i=0; $i<count($options); $i++ ) {
  $output .= '<option ' 
             . ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>' 
             . $options[$i] 
             . '</option>';
}

Sidenote: I would define a value to be some kind of id for each element, else you may run into problems, when two options have the same string representation.

like image 42
Sirko Avatar answered Sep 25 '22 12:09

Sirko