search

Home  >  Q&A  >  body text

Looking for a more elegant way to assign the "selected" attribute to a previously selected <input> element

I'm creating a simple CRUD application using PHP. On the create page, there is a drop-down menu that allows the user to select the type of highway for which they want to enter information. On the update page I want to preserve the selections the user made on the create page. The value selected by the user is stored in a local JSON object. I came up with the following solution:

<select name="route-type" id="route-type" required>

<option value="" selected="true" disabled>What type of route is this?</option>

<?php if( $highway['type'] == 'interstate') { ?>

<option value="interstate" selected>Interstate</option>
<option value="us-route">US Route</option>
<option value="state-route">State Route</option>

<?php } elseif ( $highway['type'] == 'us-route') { ?>
                
<option value="interstate">Interstate</option>
<option value="us-route" selected>US Route</option>
<option value="state-route">State Route</option>

<?php } elseif ( $highway['type'] == 'state-route') { ?>

<option value="interstate">Interstate</option>
<option value="us-route">US Route</option>
<option value="state-route" selected>State Route</option>

<?php } ?>

The problem is that this looks rather repetitive and needs to be refactored or rewritten in some way. Any suggestions? Obviously, if there are 30 choices in the drop-down list, then it's not correct to have 30 possible outcomes in the if statement.

P粉635509719P粉635509719311 days ago406

reply all(1)I'll reply

  • P粉627136450

    P粉6271364502024-01-17 19:18:26

    Here is a solution (untested):

    $options = [
      'interstate' => 'Interstate',
      'use-route' => 'US Route',
      'state-route' => 'State Route'
    ];
    
    foreach($options as $k=>$v) {
      echo "<option value=\"$k\"" . ($k===$highway['type']?'selected':'') . " />$v</option>\n";
    }
    

    reply
    0
  • Cancelreply