如何为multiselect中的每个选项添加事件处理程序?

时间:2014-05-18 16:05:23

标签: javascript jquery multi-select

我正在使用jQuery multiselect(jquery.multiselect.js)。 html标记是这样的:

    <select id ="dtDomain" title="Basic example" multiple="multiple" name="example-basic" size="3" style="width:160px">
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        <option value="option3">Option 3</option>
    </select>

我如何使用以下代码初始化多选:

$(function(){
   $("#dtDomain").multiselect({
       noneSelectedText: "select Ranges",
       checkAllText: "select all",
       uncheckAllText: 'select none',
       selectedList:4,
       minWidth:100
    });
});

现在我想为每个<option>添加事件处理程序,当选择或取消选择<option>时,将触发事件处理程序。为了实现这一点,我尝试了以下代码:

 //get the checked option and print them
 $('#dtDomain').on('change', function () {
    var array_of_checked_values = this.multiselect("getChecked").map(function(){
        return this.value; 
    }).get();
    alert(array_of_checked_values )

 })

但上面的代码效果不好,似乎这种方式无法捕捉到这个事件。谁可以给出一些建议?谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个:

var $callback = $("#dtDomain");

$("#dtDomain").multiselect({
   click: function(event, ui){
      $callback.text(ui.value + ' ' + (ui.checked ? 'checked' : 'unchecked') );
   },
   beforeopen: function(){
      $callback.text("Select about to be opened...");
   },
   open: function(){
      $callback.text("Select opened!");
   },
   beforeclose: function(){
      $callback.text("Select about to be closed...");
   },
   close: function(){
      $callback.text("Select closed!");
   },
   checkAll: function(){
      $callback.text("Check all clicked!");
   },
   uncheckAll: function(){
      $callback.text("Uncheck all clicked!");
   },
   optgrouptoggle: function(event, ui){
      var values = $.map(ui.inputs, function(checkbox){
         return checkbox.value;
      }).join(", ");

      $callback.html("Checkboxes " + (ui.checked ? "checked" : "unchecked") + ": " + values);
   }
});

检查以下内容:

http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/#callbacks