2010-09-27 25 views
1

我正在尋找一種方法將自定義選項添加到下拉選擇列表與Jquery。因此,用戶可以點擊下拉菜單,並看到一個選項列表,最後一個點擊「添加其他...」,然後他們可以輸入自己的選項(直接通過彈出窗口,彈出窗口)內聯或然而)。在代碼點火器中使用jQuery將選項添加到DropDownList

有下面的帖子解釋它,但是,我使用的配置選項作爲一個數組等。我如何可以應用此代碼點火器?

How do I add options to a DropDownList using jQuery?

謝謝!

p.s.我的知識不是很好。

回答

1

試試這個關於大小:

http://jsfiddle.net/Fh5Bz/1/

HTML

<select id="myselect"> 
    <option>hello</option> 
    <option>world</option> 
    <option>Add other...</option> 
</select> 

<div id="addother"> 
    <input type="text" id="addother_input" /> 
</div>​ 

CSS

#addother { 
    display:none; 
}​ 

JS

$(document).ready(function() { 
    $('#myselect').change(function(e) { 
     if ($(this).val() == "Add other...") { 
      $('#addother').show(); 

      //set the input back to an empty string 
      $('#addother_input').val(''); 
     } else { 
      $('#addother').hide(); 
     } 
    }); 
});​ 

編輯:對不起,錯過了它是一個CI生成的選擇元素的線。在CI,創建這樣一個選擇的元素:

$options = array(
        'small' => 'Small Shirt', 
        'med' => 'Medium Shirt', 
        'large' => 'Large Shirt', 
        'xlarge' => 'Extra Large Shirt', 
       ); 

echo form_dropdown('shirts', $options); 

如果你想創建一個額外的選項,只需把它釘住到年底,像這樣:

$options = array(
        'small' => 'Small Shirt', 
        'med' => 'Medium Shirt', 
        'large' => 'Large Shirt', 
        'xlarge' => 'Extra Large Shirt', 
        'addother' => "Add other..." 
       ); 

echo form_dropdown('shirts', $options, null, 'id="myselect"'); 

然後,在你jQuery,測試$(this).val()==「addother」而不是「Add other ...」。

+0

感謝treeface!我會試試看,還有一個很好的指向jsFiddle的指針,我以前從未見過 - 非常可愛。 – Robimp 2010-09-27 17:08:35

+0

的確,不客氣,@Robimp。我從來沒有使用CI的表單助手,所以我不能完全說出所有的細節(例如,你可能甚至不需要關聯選項數組的關聯數組,因此可以檢查「添加其他...」或者你可以簡單地使該數組鍵爲「添加其他...」或「-1」或其他)。也不完全確定form_dropdown()函數中的第三個參數。如果你不想明確選擇任何選項,我相信他們允許你在那裏放置null。 – treeface 2010-09-27 17:16:19

+0

是的,我有一點麻煩讓它工作,不知道我做錯了什麼,瀏覽器似乎是刪除我認爲的JS。我將它直接放入文檔(視圖)中,因爲它通過ajax被拉入。實際上,輸入那個,我剛剛意識到你不能通過ajax提取腳本。該死的。第三個參數用於'set_value('input_name')',然後返回在控制器進行驗證,然後到數據庫的數據庫 - 我想。我通常將它用於我的CI表單,該表單處理所有內容:http://formigniter.org/。 – Robimp 2010-09-27 17:23:50

相關問題