2017-02-25 73 views
2

我有一個多選下拉元素,其中包含複選框和該javascript元素中的更改函數。但每次單擊複選框時都會觸發更改功能。我希望只有在用戶退出選擇下拉菜單或點擊「輸入」後纔會觸發更改功能,因此如果用戶選中五個框而不是運行五次(每個新框被選中後立即執行),它只會運行一次。我怎樣才能做到這一點?這裏是我當前的代碼:如何僅在所有多選選擇完成後才觸發更改事件

html元素:

<select id="vo_select_mobile_brands" multiple="multiple"> 
     <option>Select a country</option> 
    </select> 

的JavaScript動態添加的複選框選項:

$el = $('#vo_select_mobile_brands'); 
$el.empty() 
$.each(_vo_mobile_brand_ids_list, function(idx, mobile_brand_id) { 
    $el.append($("<option></option>") 
     .attr("value", mobile_brand_id).text(mobile_brand_id)); 
}); 
$el.multiselect('destroy') 
$el.multiselect({ 
    includeSelectAllOption: true 
}); 
$el.multiselect() 

的JavaScript更改功能:

$('#vo_select_mobile_brands').change(function() { 
    _vo_selected_mobile_brands = []; 
    selected_objects = $("#vo_select_mobile_brands option:selected") 
    for(var i = 0; i < selected_objects.length; i++){ 
     //do something with the selected items 
    } 
}); 
+0

[使用Javascript - 要使用的事件多選變更]的可能的複製(http://stackoverflow.com/questions/1816755/javascript-which-event-to-use-for-multislect-change) –

回答

4

您可以執行你的js按鈕上的功能點擊按鈕click event

$('#ButtonID').click(function() { 
    _vo_selected_mobile_brands = []; 
    selected_objects = $("#vo_select_mobile_brands option:selected") 
    for(var i = 0; i < selected_objects.length; i++){ 
     //do something with the selected items 
    } 
}); 

所以它只會在用戶想要從下拉列表中選擇多個值後提交。

OR

如果您仍需要在5個項目被選中,那麼你可以選擇的值的數量來執行它的下拉菜單中更改事件和觸發功能如果選定的項目是等於5

$('#vo_select_mobile_brands').change(function() { 
    var count = $("#vo_select_mobile_brands :selected").length; 
    if(count==5) 
    alert(count); 
}); 

見琴:https://jsfiddle.net/4zabsa9e/7/

0

也許你正在尋找一個延遲,所以,如果有幾個變化在很短的時間內,你的代碼只有最後Ø後執行NE:

var timer = null; 
$('#vo_select_mobile_brands').change(function() { 
    clearTimeout(timer); // cancel and restart timer 
    timer = setTimeout(function() { 
     _vo_selected_mobile_brands = []; 
     selected_objects = $("#vo_select_mobile_brands option:selected") 
     for(var i = 0; i < selected_objects.length; i++){ 
      //do something with the selected items 
     } 
    }, 1000); // after one second of idle time 
}); 
0

所以僅觸發當選擇失去聚焦/模糊也許?:

$("#vo_select_mobile_brands").on('focusout blur',function(){ 
    //will return an array of the values for the selected options 
    var myselectedvalues = $(this).val(); 
}); 

該事件的內容的事件被髮送到一個元素時,或任何元件 在它的內部,失去了重點。這與 中的模糊事件不同,它支持檢測父元素的焦點丟失(在 中,即支持事件冒泡)。

如果您手動通過腳本更改值,你可以觸發事件:

$("#vo_select_mobile_brands").trigger("focusout"); 
+0

這是我想要的解決方案。其他解決方案(如使用計時器或添加另一個按鈕以在用戶完成選擇時進行點擊)並不理想,但可能需要做。我無法使用我正在使用的元素「專注」解決方案。只要點擊子複選框元素,父元素就會失去焦點,並且只要用戶移到下一個複選框,複選框元素就會失去焦點。我需要一些元素在用戶選擇複選框的整個過程中保持對焦狀態,然後只有在退出下拉菜單時纔會失去焦點。 –

+0

考慮使用一些自定義事件並在需要時觸發。 –

相關問題