2015-07-02 129 views
4

我試圖用隱藏屬性有選擇地隱藏下拉列表中的選項。請看看jsfiddle,我隱藏了'quietest'選項。隱藏選項在下拉列表中

$('#quietest').prop('hidden', 'hidden'); 

當單擊下拉列表中選擇「安靜」選項被成功地隱藏在箭(只有「最快」和「平衡」列),但是,用戶仍然可以選擇使用「最安靜」選項鍵盤。這是'隱藏'屬性的預期行爲嗎?如何正確隱藏,因此不再可選擇?它也需要很容易取消隱藏選項(所以最好不要刪除選項)。

+0

你會使用'.show()/。隱藏()'或'.toggle()'。雖然在某些瀏覽器中隱藏選項存在問題。你最好是使用'.prop('disabled',true | false)啓用/禁用該選項' – billyonecan

+0

@chiapa解決方案將爲你工作,如果你想阻止選項選擇而隱藏。但仍然禁用選項將顯示在下拉菜單中。如果您想同時嘗試在需要時刪除選項,並在需要顯示時添加選項。 – Yasitha

回答

3

你可以嘗試這樣的:

Fiddle - hiding with hidden property

$('#quietest').prop('disabled', true).prop('hidden', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="dptcentres_edit"> 
 
    <option value="fastest">Fastest</option> 
 
    <option selected="true" value="balanced">Balanced</option> 
 
    <option id='quietest' value="quietest">Quietest</option> 
 
</select>

編輯

由於@ billyonecan的評論,我更換了隱藏方法,而是採用hidden財產,我使用的CSS display屬性並將其設置爲none以隱藏元素。正如他正確指出的那樣,hidden屬性isn't supported by all browsers

Fiddle - Hiding with CSS display attribute

$('#quietest').prop('disabled', true).css('display', 'none');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="dptcentres_edit"> 
 
    <option value="fastest">Fastest</option> 
 
    <option selected="true" value="balanced">Balanced</option> 
 
    <option id='quietest' value="quietest">Quietest</option> 
 
</select>

+0

您最好使用'.hide()',隱藏屬性[所有瀏覽器都不支持](http://caniuse.com/#search=hidden) – billyonecan

+0

謝謝@billyonecan,我更新我的回答 – chiapa

+0

請注意,您仍然可以在鍵盤上鍵入並選擇隱藏的值。看到Raja的回答。 – Mir

0

使用hide。通過隱藏option,它不能被選擇。

$('#quietest').hide().prop('disable', true); 

DEMO

+0

這仍然有問題。您可以通過箭頭鍵選擇最安靜的。 – Yasitha

3

要停止被選中,加入disabled以及

$('#quietest').prop('disabled', true).hide(); 
相關問題