Todd Williams
Todd Williams

Reputation: 267

Dynamically generated select won't stay open

I have a select element that is populated from files on a server and is created by loading a php script. It updates properly when new files are created or deleted, but it will not stay open upon clicking. It flashes open and disappears so I don't have a chance to select an option. Is there something in my code that is causing this behavior?

Here is my form and script that calls the PHP file:

<form action="/server/php/data/process.php" method="post">
     <select class="ui mini fluid search dropdown" id="templateSelection" type="text" name="selectTemplate" style="height:30px;border:2px solid #ccc;border-radius:none;" onchange="loadTemplate()">
          <option value="" selected="selected">Select Template</option>
     </select>
</form>

<script>
  $(function() {
     $.ajaxSetup ({
         cache: false
     });
     $("#templateSelection").click(function(){
       $(this).load('select_template.php');
     });
  });
</script>

Here is select_template.php:

<?php
     foreach(glob(dirname(__FILE__) . '/server/php/data/*.json') as $filename){
     $filename = basename($filename);
     echo "<option value='" . $filename . "'>".$filename."</option>";
  }
?>

Upvotes: 0

Views: 225

Answers (1)

Felippe Duarte
Felippe Duarte

Reputation: 15131

The problem is that you are binding to a click function. That means, for every click you will reload the select. Use this script instead, to populate on page load and run only once:

$(function() {
  $.ajaxSetup ({
    cache: false
  });
  $("#templateSelection").load('select_template.php');
});

Upvotes: 1

Related Questions