2016-01-19 311 views
-1

我想要在沒有選擇任何選項時重置選擇下拉選項(默認設置爲選擇下拉選項的第一個選項,當選擇但沒有選項時焦點丟失被選中),正如你可以在下面的代碼片段中看到的,它可以重置,但問題在於,當你從選擇下拉選項中選擇一個選項時,它不會重置,然後再次單擊選擇並從選擇中失去焦點。任何想法,線索,建議,建議,請幫忙?當沒有選擇選項時重置選擇下拉選項

$(document).ready(function(){ 
 
    //restore the first option of the select dropdown option 
 
    var tt = ""; 
 
    $(document).on("focus","select",function(){ 
 
     $(this).find('option:first-child').prop({ disabled : true }).show(); 
 
     tt = $(this).val(); 
 
    }); 
 
    $(document).on("change","select",function(){ 
 
     tt = ""; 
 
     $(this).focusout(); 
 
    }); 
 

 
    $(document).on("focusout","select",function(){ 
 
     if($(this).val() === tt){ 
 
      $(this).find('option:first-child').prop({ selected : true, disabled : true }).closest("select").trigger("change"); 
 
     } 
 
     tt = ""; 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<select> 
 
    <option disabled selected>Select test</option> 
 
    <option value="1">test option 1</option> 
 
    <option value="2">test option 2</option> 
 
    <option value="3">test option 3</option> 
 
    <option value="4">test option 4</option> 
 
</select> 
 

 
<select> 
 
    <option disabled>Select test</option> 
 
    <option value="1">test option 1</option> 
 
    <option value="2">test option 2</option> 
 
    <option value="3" selected>test option 3</option> 
 
    <option value="4">test option 4</option> 
 
</select>

+0

沒明白你的問題,你可以請詳細說明更多 –

+0

運行我的片段!首先,我想要的是,如果在選擇下拉菜單時沒有選擇任何選項,那麼通過將第一個選項設置爲默認選項(選擇第一個選項爲true)來重置選擇下拉菜單,現在問題是何時你選擇選項,然後再次選擇焦點,然後失去對當前選中的焦點,選擇不重置,你必須選擇一個選項,然後聚焦和失去選擇的焦點,然後聚焦和丟失第二次選擇的重點,以重置我不想要的選擇下拉菜單。 –

+0

當你選擇一個選項並再次點擊選擇時,選擇不會失去它的焦點,它只是關閉下拉菜單。在點擊其他東西之後,它就失去了焦點。由於沒有進行更改,因此重置。 – Nomeaning25

回答

0
$(document).ready(function(){ 
    //restore the first option of the select dropdown option 
    var tt = ""; 
    var open = false; 
    $(document).on("focus","select",function(){ 
     if(open) { 
      open = false; 
     } 
     $(this).find('option:first-child').prop({ disabled : true }).show(); 
     tt = $(this).val(); 
    }); 
    $(document).on("change","select",function(){ 
     tt = ""; 
     $(this).blur(); 
    }); 

    $(document).on("blur","select",function(){ 
     if($(this).val() === tt){ 
      $(this).find('option:first-child').prop({ selected : true, disabled : true }).closest("select").trigger("change"); 
     } 
     tt = ""; 
    }); 
    //When the dropdown closes it blures the select. Catuion this will also trigger 
    //if you open select and select nothing and close it back. In that case the select 
    //will be reset. 
    $(document).on("click","select",function(){ 
     open = !open;  
     if(!open){ 
      $(this).blur(); 
     } 
    }); 
});