2016-09-21 30 views
1

我正在使用bootstrapselectpicker插件。現在我想找到最後選擇或取消選擇哪個選項。如何在canJs中的bootstrap的selectpicker插件中查找選擇哪個選項?

<select class="selectpicker selection-criteria" multiple> 
    <option value="0" selected>Mustard</option> 
    <option value="1" selected>Ketchup</option> 
    <option value="2" selected>Relish</option> 
</select> 

現在,我甚至不能在canJs觸發任何時候任何optionselecteddeselected。但是我可以在整個選擇器上觸發事件。

".selection-criteria change": function(el,ev){ 
    val colNames = $(el).val() // it returns all the selection options value 
} 

但是,我可以觸發selectpicker的選項點擊任何事件?當任何選項被改變時,我會得到該選項,並知道它現在被選中或取消選擇?我可以在canJs做到嗎?

編輯:如果我選擇或取消選擇選項0,那麼我想這個元素即

<option value="0" selected>Mustard</option> 

它是否現在選擇或取消選擇,現在,我會隱藏一些div的基礎。

+0

你想擁有所有選定的選項還是你想確切地知道什麼是最後的選擇或取消選擇的東西?最後你想達到什麼目的? –

+0

我想知道上次選擇或取消選擇的選項 –

+0

您是使用can.Component還是can.Control? –

回答

1

這會給你使用jQuery上改變所有選擇的選項。

$('.selectpicker').change(function() { 
    var selectedText = $(this).find("option:selected").text(); 

    alert(selectedText); 
}); 

如果你想要最後一個選定的值,你可以將它們推到一個數組並獲取最新的ID。 (參考:how to get the clicked option in bootstrap selectpicker?

https://jsfiddle.net/96stvL6f/

+0

我想你不明白我的問題。但是,如果有一個選項是之前選擇的,現在我已取消選擇它。所以我想要取消選擇的選項元素。它被選中或取消選擇並不重要。重要的是哪個選項現在正好改變。 –

2

您應該將<select>的值綁定到你的視圖模型的屬性。然後,通過爲該屬性定義一個setter,您可以訪問舊值和新值。我編寫了代碼,以確定哪些項目是新選擇的,哪些項目是使用lodash取消選擇的。

http://jsbin.com/pobukubari/1/edit?html,js,output

<select {($value)}="selectedOptions" class="selectpicker selection-criteria" multiple> 
    <option value="0" selected>Mustard</option> 
    <option value="1" selected>Ketchup</option> 
    <option value="2" selected>Relish</option> 
    <option value="3" selected>Onions</option> 
    <option value="4" selected>Sauerkraut</option> 
</select> 

...然後在您的視圖模型:

can.Component.extend({ 
    tag: "my-component", 
    template: can.view('my-component-template'), 
    viewModel: can.Map.extend({ 
    define: { 
     selectedOptions: { 
     set: function (newItems) { 
      var prevItems = this.attr('selectedOptions'); 
      var union = _.union(prevItems, newItems); 
      var selected = _.difference(union, prevItems); 
      var deselected = _.difference(union, newItems); 
      console.log('You just selected these new items:', selected.join(', ')); 
      console.log('You just deselected:', deselected.join(', ')); 
      return newItems; 
     } 
     } 
    } 
    }) 
}); 
相關問題