【问题标题】:Prevent space in tag text of select2防止 select2 的标签文本中出现空格
【发布时间】:2019-02-08 17:21:21
【问题描述】:

我在 select2 中创建没有空格的标签时遇到了一些问题。当我按喜欢 tt 然后创建一个新标签时,如果我再次写 tt 它会阻止但当我按“tt tt”然后创建新标签时。我想防止两个 tt 和 tt 之间有空格。此标签中不允许有空格。我怎么能那样做?提前致谢。

代码

$(document).ready(function() {
      $("#pictures_tag_input").select2({
        tags: true,
        multiple: true,
        placeholder: "Please type here",
        maximumSelectionSize: 12,
        minimumInputLength: 2,
        tokenSeparators: [",", " "],
        createTag: function(params) {
          // empty string is not allow
          var term = $.trim(params.term);
          if (term === "") {
            return null;
          }
    
          // duplicate check
          var selectedTags = $("#pictures_tag_input").val() || [];
          if (selectedTags.indexOf(term) > -1) {
            return null;
          }
    
          return {
            id: term,
            text: term,
            newTag: true // add additional parameters
          };
        },
        templateResult: function(item) {
          return item.name || item.text;
        },
        templateSelection: function(item) {
          return item.name || item.text;
        },
        escapeMarkup: function(markup) {
          return markup;
        },
        ajax: {
          url: "https://api.myjson.com/bins/444cr",
          dataType: "json",
          global: false,
          cache: true,
          delay: 0,
          data: function(params) {
            return {
              q: params.term
            };
          },
          processResults: function(results, params) {
            // remove existing tag after key press
            var term = $.trim(params.term);
            var searchedTags = $.map(results, function(tag) {
              if (tag.text.match(term) || term === "")
                return { id: tag.id, text: tag.text };
            });
            return {
              results: searchedTags
            };
          } //end of process results
        } // end of ajax
      });
    });
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>


<div class="container">
  <form id="frm">
    <h1>Sample Form</h1>
    <div class="row">
      <div class="col-4">
        <div class="form-group">
          <label for="tagInput">Tag Input</label>
          <select class="form-control" id="pictures_tag_input"></select>
          <small class="form-text text-muted"><p class="text-info">1) no space in tag 2) create tag dynamically 3) prevent duplicate tag 4) search tag from ajax calling 5) tag create by enter, space and comma 6) at first dot, @ are not allow 7) sometimes tag popup position is not right placed.</p></small>
        </div>
      </div>
    </div>
  </form>
</div>

注意:select2 版本是 4.0.5

这是demo 链接 https://codepen.io/mdshohelrana/pen/daVZNo?editors=1010

【问题讨论】:

    标签: javascript jquery ajax jquery-select2


    【解决方案1】:

    ...我想防止两个 tt 和 tt 之间有空格。 您可以通过两种不同的方式实现它:

    第一种方法: 在您的创建标签中搜索以.....开头的元素来自:

    if (selectedTags.indexOf(term) > -1) {
       return null;
    }
    

    到:

    var dups = selectedTags.findIndex(function(e) {
           return e  == term.substr(0, e.length + 1).trim();
    })
    

    第二种方法: 使用select2:selecting 以防止新标签以不需要的前缀开头:

    .on('select2:selecting', function(e) {
        if (e.params.args.data.newTag) {
            var term = e.params.args.data.text;
            var selectedTags = $("#pictures_tag_input").val() || [];
            var dups = selectedTags.findIndex(function(e) {
                return e  == term.substr(0, e.length + 1).trim();
            })
            if (dups != -1) {
                e.preventDefault();
            }
       }
    });
    

    这样,如果您只想避免新标签中出现空格,您可以简单地阻止新标签文本中包含空格时的默认操作。

    $("#pictures_tag_input").select2({
        tags: true,
        multiple: true,
        placeholder: "Please type here",
        maximumSelectionSize: 12,
        minimumInputLength: 2,
        tokenSeparators: [",", " "],
        createTag: function (params) {
            // empty string is not allow
            var term = $.trim(params.term);
    
            if (term === "") {
                return null;
            }
    
            // duplicate check
            var selectedTags = $("#pictures_tag_input").val() || [];
            var dups = selectedTags.findIndex(function (e) {
                return (e.length <= term.length) && (e == term.substr(0, e.length + 1).trim());
            })
            if (dups != -1) {
                return null;
            }
    
            return {
                id: term,
                text: term,
                selected: true,
                newTag: true // add additional parameters
            };
        },
        templateResult: function (item) {
            return item.name || item.text;
        },
        templateSelection: function (item) {
            return item.name || item.text;
        },
        escapeMarkup: function (markup) {
            return markup;
        },
        ajax: {
            url: "https://api.myjson.com/bins/444cr",
            dataType: "json",
            global: false,
            cache: true,
            delay: 0,
            data: function (params) {
                return {
                    q: params.term
                };
            },
            processResults: function (results, params) {
                // remove existing tag after key press
                var term = $.trim(params.term);
                var searchedTags = $.map(results, function (tag) {
                    if (tag.text.match(term) || term === "")
                        return {id: tag.id, text: tag.text};
                });
                return {
                    results: searchedTags
                };
            } //end of process results
        } // end of ajax
    }).on('select2:selecting', function (e) {
        if (e.params.args.data.newTag) {
            var term = e.params.args.data.text;
            var selectedTags = $("#pictures_tag_input").val() || [];
            var dups = selectedTags.findIndex(function (e) {
                return (e.length < term.length) && (e == term.substr(0, e.length + 1).trim());
            })
            if (dups != -1) {
                e.preventDefault();
            }
        }
    }).on('select2:opening', function (e) {
        var val = $(this).data().select2.$container.find('input');
        if ($(this).val().indexOf(val.val()) != -1) {
            val.val('');
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
    
    
    <div class="container">
        <form id="frm">
            <h1>Sample Form</h1>
            <div class="row">
                <div class="col-6">
                    <div class="form-group">
                        <label for="pictures_tag_input">Tag Input</label>
                        <select class="form-control" id="pictures_tag_input">
                        </select>
                        <small class="form-text text-muted"><p class="text-info">1) no space in tag 2) create tag dynamically 3) prevent duplicate tag 4) search tag from ajax calling 5) tag create by enter, space and comma 6) at first dot, @ are not allow 7) sometimes tag popup position is not right placed.</p></small>
                    </div>
                </div>
            </div>
        </form>
    </div>

    【讨论】:

    • 兄弟,我的其他功能丢失了,请通过以下方式检查。只需键入“tag”并按空格键,然后键入“tag”并选择任何值 tag2、tag3,然后查看错误。 “标签”是重复的。请帮帮我。
    • @Shohel 嗨朋友,抱歉耽搁了,我删除了 sn-p anf 中的评论,现在它可以工作了。评论: if (dups != -1) return null;告诉我谢谢
    • 老哥,先选择“tag1”然后输入“tag”,这里是选择问题,选择了“tag1”但需要选择“tag”。我怎么能这样兄弟?
    • @Shohel 为我的 sn-p 添加了一个小修复。我希望这可以帮助你
    【解决方案2】:

    只删除标签中的所有空格?

    var term = $.trim(params.term).replace(/\s/g,'');
    

    然后tt tt 将变为tttt,其余功能仍然有效。申请你的 codepen:https://codepen.io/anon/pen/zeRoOv?editors=1010

    【讨论】:

      【解决方案3】:

      只需添加以下代码:

      $(document).on('keydown',".select2-search__field",function(e){  
         if (e.which === 32)  
            return false;  
      });
      

      使用Keydown 事件。当一个键被按下时,该函数将获得keycode
      该条件将检查keycode,如果按下空格键,它将返回false。
      这将“禁用”空格键并防止 select2 的标签文本中出现空格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-23
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-12
        • 1970-01-01
        相关资源
        最近更新 更多