2011-02-04 114 views
4

我有這樣的代碼:jQuery的塊<select>先選擇

<select name="aa"> 
    <option>a</option> 
    <option>b</option> 
    <option>c</option> 
</select> 

有辦法阻止打開選擇我的所有形式的,並只顯示在這個例子中只有一個第一選擇?

在此先感謝 僑^h

回答

7

刪除與:gt(0)過濾(0)所有其他選項是這樣的指標:

$("select[name='aa'] option:gt(0)").remove(); 

或禁用它們像這樣:

$("select[name='aa'] option:gt(0)").attr("disabled", "disabled"); 

並使用:eq(0)過濾器選擇一個項目(0)是索引這樣的:

$("select[name='aa'] option:eq(0)").attr("selected", "selected"); 

反向可以與:not濾波器來完成:

$("select[name='aa'] :not(option:gt(0))").attr("disabled", "disabled"); 

:lt濾波器:

$("select[name='aa'] option:lt(1)").attr("disabled", "disabled"); 

只是分配一個空字符串.attr("disabled", "");.attr("selected", "");刪除屬性設置。

fiddle here

翻轉/觸發器值我想你需要第二個(隱藏)選擇:

fiddle here

// hide items 
var src = $("select[name='aa'] option:eq(0)"); 
var tar = $("select[name='ab']").hide(); 

tar.append(src.clone()) 
src.remove(); 


//reshow items: 
src = $("select[name='ab'] option:eq(0)"); 
tar = $("select[name='aa']") 

tar.prepend(src.clone()) 
src.remove(); 
+0

那似乎解決方案,但我可以扭轉它?再次感謝! – haltman 2011-02-04 08:26:21

+0

@haltman也許你可以使用hide()和show()而不是remove() – Tx3 2011-02-04 08:34:01

1

什麼?你的意思是選擇默認選項?嘗試使用的一個選項,選擇屬性

<option selected>a</option> 

或作出不可選擇一個選項:

<option disabled>a</option> 
1

,你可以這樣做:

$("select[name='aa']").val($("select[name='aa'] option:first").val()); 
1

您可以禁用那些你不不希望能夠被選中,或者你可以改變他們的CSS顯示,如:

$('select[name="aa"] option').not(':first').css('display','none'); 
如果你想自動設置爲「默認」值,不要讓任何人改變它,你可以設置第一個的值,然後關閉整個選擇的元素,這樣沒有人改變它

$('select[name="aa"]') 
    // set the value of the first option 
    .val($('select[name="aa"] option:first').val()) 
    // disable the select element so that no one can alter it's value 
    .attr('disabled','disabled');