允许使用selected.js多选的新值

时间:2011-09-12 08:41:30

标签: jquery jquery-chosen multiple-select

我正在使用带有jQuery的selected.js插件http://harvesthq.github.com/chosen/来允许用户从select中选择多个选项。但是,我现在希望能够让他们创建尚未存在的值 - 任何想法如何解决这个问题?

编辑:与SO自己的标签选择/创建栏类似的东西将接近我所追求的

最好不要更改或编辑插件,但如果需要,也可以。

代码: HTML:

<p>Select something</p>
<select name="theSelect[]" multiple="multiple">
    <option value="First Option">First Option</option>
    <option value="Second Option">Second Option</option>
</select>

使用Javascript:

$(function(){
    $('select').chosen();
});

因此,如果用户输入“第三选项”,我想将其添加到列表中并选择它。值和显示名称是/将是相同的,所以这不是一个问题

10 个答案:

答案 0 :(得分:24)

根据文档,您可以尝试这样做:

$('select').append('<option>test</option>');
$('select').trigger('liszt:updated');

Tony在下面的评论中说:

“从版本1.0开始,现在选择了触发器:已更新”。请参阅harvesthq.github.io/chosen/#change-update-events

答案 1 :(得分:19)

我偶然发现了同样的想法。 看起来它是一个非常受欢迎的功能请求,并且有几个叉实现了它。看起来它很快就会合并到主分支中。

+1这个特殊的拉动有魅力: https://github.com/harvesthq/chosen/pull/166

您可以在此处查看Koenpunt的分叉:https://github.com/koenpunt/chosen

答案 2 :(得分:11)

这是我做到的一种简单方法:

$(".search-field").find("input").live( "keydown", function (evt) {
    var stroke;
    stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
    if (stroke == 9) { // 9 = tab key
        $('#tags').append('<option value="' + $(this).val() + '" selected="selected">' + $(this).val() + '</option>');
        $('#tags').trigger('chosen:updated');
    }
});

答案 3 :(得分:10)

我只是想解决同样的问题。我稍微修改了源代码。这是新的keyup_checker函数。看一下案例13:

AbstractChosen.prototype.keyup_checker = function(evt) {
  var stroke, _ref;
  stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
  this.search_field_scale();
  switch (stroke) {
    case 8:
      if (this.is_multiple && this.backstroke_length < 1 && this.choices > 0) {
        return this.keydown_backstroke();
      } else if (!this.pending_backstroke) {
        this.result_clear_highlight();
        return this.results_search();
      }
      break;
    case 13:
      evt.preventDefault();
      if (this.results_showing) {
        if (!this.is_multiple || this.result_highlight) {
          return this.result_select(evt);
        }  

        $(this.form_field).append('<option>' + $(evt.target).val() + '</option>');
        $(this.form_field).trigger('liszt:updated');
        this.result_highlight = this.search_results.find('li.active-result').last();
        return this.result_select(evt);
      } 
      break;
    case 27:
      if (this.results_showing) this.results_hide();
      return true;
    case 9:
    case 38:
    case 40:
    case 16:
    case 91:
    case 17:
      break;
    default:
      return this.results_search();
  }
};

答案 4 :(得分:5)

我知道这不是答案,而是另一种解决方案。

我正在搜索即时添加部分,发现http://ivaynberg.github.com/select2/#tags提供的内容与选择+“标记”等其他内容相同。

答案 5 :(得分:4)

您可以将事件附加到输入文本框以侦听特定字符代码。之后添加选项并在下拉列表中触发更新。

 var dropDown = $('select.chosen');
 dropDown.parent().find('.chzn-container .chzn-search input[type=text]').keydown( function (evt) {
           var stroke, _ref, target, list;
           // get keycode
           stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
           target = $(evt.target);               
           // get the list of current options
           list = target.parents('.chzn-container').find('.chzn-choices li.search-choice > span').map(function () { return $(this).text(); }).get();
           if (stroke === 9 || stroke === 13) {
              var value = $.trim(target.val());
              // if the option does not exists
              if ($.inArray(value,list) < 0) {
                 var option = $('<option>');
                 option.text(value).val(value).appendTo(dropDown);
                 option.attr('selected','selected');
                 // add the option and set as selected
              }
              // trigger the update event
              dropDown.trigger("liszt:updated");
              return true;
           }
        });

答案 6 :(得分:1)

leogdion答案的更新,适用于所选的更高版本:

        var dropDown = $('#select_chosen');
        // Make the chosen drop-down dynamic. If a given option is not in the list, the user can still add it
        dropDown.parent().find('.chosen-container .search-field input[type=text]').keydown( 
            function (evt) {
               var stroke, _ref, target, list;
               // get keycode
               stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
               // If enter or tab key
               if (stroke === 9 || stroke === 13) {
                   target = $(evt.target);               
                   // get the list of current options
                   chosenList = target.parents('.chosen-container').find('.chosen-choices li.search-choice > span').map(function () { return $(this).text(); }).get();
                   // get the list of matches from the existing drop-down
                   matchList = target.parents('.chosen-container').find('.chosen-results li').map(function () { return $(this).text(); }).get();
                   // highlighted option
                   highlightedList = target.parents('.chosen-container').find('.chosen-results li.highlighted').map(function () { return $(this).text(); }).get();
                   // Get the value which the user has typed in
                   var newString = $.trim(target.val());
                   // if the option does not exists, and the text doesn't exactly match an existing option, and there is not an option highlighted in the list
                   if ($.inArray(newString,matchList) < 0 && $.inArray(newString,chosenList) < 0 && highlightedList.length == 0) {
                     // Create a new option and add it to the list (but don't make it selected)
                     var newOption = '<option value="' + newString + '">' + newString + '</option>';
                     $("#select").prepend(newOption);
                     // trigger the update event
                     $("#select").trigger("chosen:updated");
                     // tell chosen to close the list box
                     $("#select").trigger("chosen:close");
                     return true;
                  } 
                  // otherwise, just let the event bubble up
                  return true;
               }
            }
        )

答案 7 :(得分:1)

我再次更新了3nochroot的代码。现在我只有一个选择器来查找多选输入。

$(document).ready(function() {
$(".js-choicelist").chosen({
    //config comes here
}).parent().find('.chosen-container .search-field input[type=text]').keydown(
    function (evt) {
        var stroke, _ref, target, list;
        // get keycode
        stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
        // If enter or tab key
        if (stroke === 9 || stroke === 13) {
            target = $(evt.target);
            // get the list of current options
            chosenList = target.parents('.chosen-container').find('.chosen-choices li.search-choice > span').map(function () { return $(this).text(); }).get();
            // get the list of matches from the existing drop-down
            matchList = target.parents('.chosen-container').find('.chosen-results li').map(function () { return $(this).text(); }).get();
            // highlighted option
            highlightedList = target.parents('.chosen-container').find('.chosen-results li.highlighted').map(function () { return $(this).text(); }).get();
            // Get the value which the user has typed in
            var newString = $.trim(target.val());
            // if the option does not exists, and the text doesn't exactly match an existing option, and there is not an option highlighted in the list
            if ($.inArray(newString,matchList) < 0 && $.inArray(newString,chosenList) < 0 && highlightedList.length == 0) {
                // Create a new option and add it to the list (but don't make it selected)
                var newOption = '<option value="' + newString + '">' + newString + '</option>';
                var choiceSelect = target.parents('.select-multiple').find('select');
                choiceSelect.prepend(newOption);
                // trigger the update event
                choiceSelect.trigger("chosen:updated");
                // tell chosen to close the list box
                choiceSelect.trigger("chosen:close");
                return true;
            }
            // otherwise, just let the event bubble up
            return true;
        }
    }
)

})

答案 8 :(得分:0)

针对多项选择(gist)更新Leogdion答案

  $(".chosen-select-with-add-new").chosen({
    no_results_text: "Click Enter or Tab to add new option",
    width: '100%'
  }).parent().find('.chosen-container .search-field input[type=text]').keydown(function (evt) {
    // get keycode
    const stroke = evt.which != null ? evt.which : evt.keyCode;
    // If enter or tab key
    if (stroke === 9 || stroke === 13) {
      const target = $(evt.target);
      // get the list of current options
      const chosenList = target.parents('.chosen-container').find('.chosen-choices li.search-choice > span').map(function () { return $(this).text(); }).get();
      // get the list of matches from the existing drop-down
      const matchList = target.parents('.chosen-container').find('.chosen-results li').map(function () { return $(this).text(); }).get();
      // highlighted option
      const highlightedList = target.parents('.chosen-container').find('.chosen-results li.highlighted').map(function () { return $(this).text(); }).get();
      // Get the value which the user has typed in
      const newString = $.trim(target.val());
      // if the option does not exists, and the text doesn't exactly match an existing option, and there is not an option highlighted in the list

      if ($.inArray(newString, matchList) < 0 && $.inArray(newString,chosenList) < 0 && highlightedList.length == 0) {
        // Create a new option and add it to the list (but don't make it selected)
        const newOption = '<option value="' + newString + '" selected="selected">' + newString + '</option>';
        const choiceSelect = target.parents('.chosen-container').siblings('.chosen-select-with-add-new');
        choiceSelect.append(newOption);
        // trigger the update event
        choiceSelect.trigger("chosen:updated");
        // tell chosen to close the list box
        choiceSelect.trigger("chosen:close");
        return true;
      }
      // otherwise, just let the event bubble up
      return true;
    }
  })

在导轨(细长型)上的用法示例

  .tag-list
    label.control-label.h5 Tag list
    = select_tag :tag_list, options_for_select(ActsAsTaggableOn::Tag.order('taggings_count desc').pluck(:name), @publication.tags.map(&:name)), multiple: true, data: { placeholder: 'north, east, south, west' }, class: 'chosen-select-with-add-new'

答案 9 :(得分:0)

我尝试了这里和其他地方提供的几种解决方案,但是在choed.js 1.8.5(jQuery:3.3.1)中都无法解决问题,因此我结束了以下内容,因为我不想使用可能不会使用的fork始终是最新的master分支:

对于不希望任何.chosen-select允许新值的情况,我添加了一个新类.chosen-newValuesAllowed。我在此类上设置了一个事件处理程序,其中 CTRL + I 添加新值(如果尚不存在)。之后,对输入字段的关注不会丢失。在我的示例中,由于@value实际上包含数据库ID,因此我检查了innerHTML,因此新值(在我的示例中为字符串,稍后将由服务器处理)在@value中永远找不到。如果要检查@value,请参见代码片段中的注释。 该代码处理单个和多个选择。

$(document).on("keydown", ".chosen-container.chosen-newValuesAllowed input", function(e) { 
if (e.ctrlKey === true && e.keyCode === 73) { // CTRL + I
    e.preventDefault();
    var newValue = $(this).val();
    if (newValue) {            
        try {
            // only add if there is no option having the content/text of "input" yet!
            // instead of filter() for the content of <option> you can check on its @value by: find("option[val='...']") 
            var $selectElement = $(e.target).closest("div.chosen-container").prev(); // the previous sibling should be the <select>. If not, grab it some other way, e.g. via @id
            if (!$selectElement.find("option").filter(function () { return $(this).html() === newValue; }).length) {
                if (!$selectElement.attr("multiple")) { // unselect for single-select 
                    $selectElement.val('');
                }
                $selectElement.append('<option val="' + newValue + '" selected>' + newValue + '</option>');
                $selectElement.trigger('chosen:updated');    
            }
        } catch(error) {
            // pass
        }
        e.target.focus();
    }        
    return false; 
}
});

另一种解决方案是,如果仅在明确没有结果的情况下才添加新值,则调用可触发函数 chosen:no_results

$(".chosen-select.chosen-newValuesAllowed").on("chosen:no_results", function(e, data){
       var newValue = data.chosen.get_search_text();
       ...
 });