2017-06-02 225 views
1

這是從php文件中動態加載的下拉框。我已經設置了一個默認選項Select Language但是,一旦加載了ajax元素,就不會顯示這個選項。默認選擇不在下拉菜單中顯示

即使加載ajax項目後,如何將選擇語言設置爲默認值?

<select id="name"> 
    <option style="display:none;" selected>Select language</option> 
</select> 

<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?> 

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 
    <script> 
     $.ajax({ 
      type: "POST", 
      data: {place: '<?= $_GET["place"] ?>'}, 
      url: 'listplace.php', 
      dataType: 'json', 
      success: function (json) { 
       if (json.option.length) { 
        var $el = $("#name"); 
        $el.empty(); // remove old options 
        for (var i = 0; i < json.option.length; i++) { 
         $el.append($('<option>', 
          { 
           value: json.option[i], 
           text: json.option[i] 
          })); 
        } 
       }else { 
        alert('No data found!'); 
       } 
      } 
     }); 
    </script> 
+1

刪除此行'$ el.empty();'形成你的ajax。 –

+0

由於'$ el.empty();'。它刪除所有選項。 – Shubham

回答

2

$el.empty()語句從select所有選項。你不應該刪除第一個選項。

爲此,請使用not方法和:first僞類以保持默認選項。

$el.find('option').not(':first').remove(); 
1

因爲您需要刪除舊的選項,並沒有鬆動的默認添加新的「選擇語言」的文字,你可以這樣做:

<select id="name"> 
 
    <option style="display:none;" selected>Select language</option> 
 
</select> 
 

 
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?> 
 

 
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 
 
    <script> 
 
     $.ajax({ 
 
      type: "POST", 
 
      data: {place: '<?= $_GET["place"] ?>'}, 
 
      url: 'listplace.php', 
 
      dataType: 'json', 
 
      success: function (json) { 
 
       if (json.option.length) { 
 
        var $el = $("#name"); 
 
        $el.empty(); // remove old options 
 
        //adding your default value 
 
        $el.append('<option selected>Select language value</option>'); 
 
        for (var i = 0; i < json.option.length; i++) { 
 
         $el.append($('<option>', 
 
          { 
 
           value: json.option[i], 
 
           text: json.option[i] 
 
          })); 
 
        } 
 
       }else { 
 
        alert('No data found!'); 
 
       } 
 
      } 
 
     }); 
 
    </script>