2014-05-14 34 views
4

我正在使用數據列表,並且需要檢測用戶何時從下拉列表中選擇一些內容。 A similar question has been asked但我需要它,以便事件只在用戶從數據列表中選擇一些事件時觸發。如果他們在輸入中鍵入內容,那麼我不希望事件觸發。 (注意在我接受的問題的答案中,我將它們綁定了輸入,這不是我想要的)。我試過(沒有成功):如何獲取數據列表的更改事件?

<datalist> 
    <option>Option 1 Here</option> 
    <option>Option 2 Here</option> 
</datalist> 


$(document).on('change', 'datalist', function(){ 
    alert('hi'); 
}); 

編輯: 這個問題比提出的問題不同,因爲它是一個完全不同的問題。

+0

我已經搜查了很多,似乎沒有任何* *正常的方法來做到這一點。你可以使用'jQuery UI'的'Autocomplete'小部件代替:http://jqueryui.com/autocomplete/ –

+1

你可以使用這個小腳本:https://github.com/aFarkas/remote-list。雖然它是爲創建自動建議創建動態數據列表而編寫的,但它也可以處理靜態數據。這裏是一個小提琴:http://jsfiddle.net/trixta/p8LRM/。 (docu:https://github.com/aFarkas/remote-list#select-function and demo:http://afarkas.github.io/remote-list/demo/index.html) –

+0

可能重複的[Get selected在datalist使用jQuery](http://stackoverflow.com/questions/22844373/get-selected-value-in-datalist-using-jquery) –

回答

6

您可以在更改時手動檢查它。但是你需要檢查datalist輸入的變化。

$(document).on('change', 'input', function(){ 
    var options = $('datalist')[0].options; 
    var val = $(this).val(); 
    for (var i=0;i<options.length;i++){ 
     if (options[i].value === val) { 
      alert(val); 
      break; 
     } 
    } 
}); 

FIDDLE

相關問題