2014-10-07 43 views
0

我有這個選擇下拉菜單中,我使用引導選:自舉 - 選擇獲取有關更改事件最新選定的選項

http://silviomoreto.github.io/bootstrap-select/

<select id="properties" name="properties[]" class="selectpicker" data-live-search="true" multiple> 
</select> 

$(document).ready(function() { 

    // instantiating the main properties 
    loadProperties(0); 

$('#properties').on('change', function(){ 
    var optionSelected = $("option:selected", this); 
    alert(optionSelected.data('parent')); 
}); 

}); 

function loadProperties(param) { 
    var propSelect = $('#properties'); 

    $.get("json/" + param + ".json",function(options,status){ 
    $.each(options, function(val, text) { 
     var option = $('<option data-parent="' + param + '" class="prop-option"></option>').val(val).html(text); 
     propSelect.append(option); 
    }); 
    $('.selectpicker').selectpicker('refresh'); 
    }); 
} 

的問題是,我需要得到的最後一個選項選中而不是每個選定的選項。 我只能使用on change方法,因爲Bootstrap-select不會在選項上返回任何點擊事件。

如何使用on Change事件獲取最後選擇的選項?

感謝您的時間

回答

0

試試這個:你最後一次選擇的選項存儲爲一些data屬性,可以說data-prev和更新,每change事件。請參見下面的代碼 -

$(document).ready(function() { 

    // instantiating the main properties 
    loadProperties(0); 

    $('#properties').on('change', function(){ 
    var optionSelected = $("option:selected", this); 
    //read last selected value 
    var lastSelected = $(this).data('prev'); 
    alert(lastSelected); 
    //update last selected value 
    $(this).data('prev',optionSelected.data('parent')); 
    alert(optionSelected.data('parent')); 
    }); 

}); 
+0

它不工作;(它不添加在所有 – Anonymous 2014-10-07 10:50:00

+0

新的數據屬性如果您正在檢查DOM查看數據屬性,那麼它是不可見的,你必須使用'.attr ('data-prev',val)'而不是'.data('prev',val)' – 2014-10-07 10:53:41

+0

我解決了這個問題:var parent_id = $(「option:selected:last」,this).val ); – Anonymous 2014-10-07 13:07:59