Home > front end >  Drop down field does not show saved value as selected
Drop down field does not show saved value as selected

Time:11-14

My site is built with Codeigniter, and I'm trying to fix an error with saving a field. My select input will save to the database and display on the front end of the site, but if I revisit the page to make any changes, the dropdown resets to the default empty field and I need to re-select the proper option. The text fields all save properly and as expected.

Here is the form field that is not saving the selection

     <div class="col-md-3">
          <label>Condition</label> 
          <select data-placeholder="Choose Condition..." class=" select-search" tabindex="2"  name="condition">
             <option value=""></option>
             <option value="New">New</option>
             <option value="Used">Used</option>
          </select>
     </div>

Here is a text field that does work and save as expected

    <div class="col-md-3">
         <label>Year</label> 
         <input type="text" name="year"  class="form-control" value="<?php if(isset($result['year'])){echo $result['year'];};?>">
    </div>

And lastly here is some PHP that might be relevant? This is at the top of the page.

    <?php
$arr = array();
if (isset($result)) {
    $id = $result['id'];
    $parent_id = $result['parent_id'];
    $path = admin_url('vehicles/update');
} else {
  $id = '';
  $parent_id = '';
    $path = admin_url('vehicles/save');
}
?>

CodePudding user response:

You need a select one option, someting like are you doing on input for a car year.

Check what type of condition is (new or used) and select it you can do it like this use this site for help https://www.w3schools.com/tags/att_option_selected.asp

 
<div class="col-md-3">
  <label>Condition</label> 
  <select data-placeholder="Choose Condition..." class=" select-search" tabindex="2"  name="condition">
     <option value=""></option>
      <?php 
           if($result['codition'] == 'new'){ 
               $new_selected = 'selected';
               $used_selected = '';
            }else{
               $new_selected = '';
               $used_selected = 'selected';
            }
      ?>
     <option value="New" <?php echo $new_selected; ?> >New</option>
     <option value="Used" <?php echo $used_selected; ?> >Used</option>
   </select>
 </div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

you have to use one line if inside the options.

<option value=""></option>
<option value="New" <?= (isset($result['condition']) && ($result['condition']!=''))? 'selected' : NULL ?> >New</option>
<option value="Used" <?= (isset($result['condition']) && ($result['condition']!=''))? 'selected' : NULL ?> >Used</option>
  • Related