[英]On select change always display first disabled option
我有幾種選擇的簡單選擇:
<select id = "actionslist">
<option id="selectoption" disabled selected>Select</option>
<option value = "Remove Plans">Remove Plans</option>
<option value = "Something else">Something Else</option>
</select>
我的問題是,當我單擊“刪除計划”時,我的onchange事件開始了,並且在選擇窗口中看到了它,而不是首先禁用的選定選項“選擇”。 我如何始終將“選擇”保留在選擇窗口中,讓用戶重新選擇他們想要的任何選項,而無需實際“選擇”它並顯示在選擇窗口中。
$('#actionslist').bind("change", function () {
var item = $(this).val();
if (item === "Remove Plans")
{
//do something
}
});
同樣,我希望始終顯示“選擇”,而不是用戶單擊的選項。 但是,我不希望“選擇”成為用戶可以單擊的選項之一。
這里的想法是確保onchange事件始終啟動,即使用戶不斷重復選擇相同的選項也是如此。
謝謝!
您可以在on change事件期間將其重置。 $(this).prop('selectedIndex',0)
。 但是,您現在必須引用該值(基本上將其存儲在變量中)。 現在,select元素將具有原始值。
$( "#actionslist" ).bind( "change", function() { console.log(this.value) if (this.value === "Remove Plans") { //do something } $(this).prop('selectedIndex',0); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id = "actionslist"> <option id="selectoption" disabled selected>Select</option> <option value = "Remove Plans">Remove Plans</option> <option value = "Something else">Something Else</option> </select>
這可以輕松完成–只需添加this.selectedIndex = 0;
在變更功能結束時
$('#actionslist').bind("change", function () { var item = $(this).val(); console.log(item) if (item === "Remove Plans") { //do something } this.selectedIndex = 0; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id = "actionslist"> <option id="selectoption" disabled selected>Select</option> <option value = "Remove Plans">Remove Plans</option> <option value = "Something else">Something Else</option> </select>
創建(覆蓋實際選擇框的)不可點擊的選擇框是(快速,骯臟的)解決方案之一。 但是,您必須注意確保它們重疊:
$('#fakeActionslist').bind("change", function() { $('#actionslist').val($(this).val()); $(this).val(''); alert($('#actionslist').val()); // User's latest choice is saved in $('#actionslist').val() });
.select-container { position: relative; } #fakeActionslist { z-index: 1; position: absolute; left: 0; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="select-container"> <select id="actionslist"> <option value="" disabled selected>Select</option> <option value="Remove Plans">Remove Plans</option> <option value="Something else">Something Else</option> </select> <select id="fakeActionslist"> <option value="" disabled selected>Select</option> <option value="Remove Plans">Remove Plans</option> <option value="Something else">Something Else</option> </select> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.