2016-01-19 202 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(); 
     } 
    }); 
});