Select2标签用下划线替换空格

时间:2016-10-03 22:45:52

标签: javascript jquery jquery-select2

我有一个用于执行标记的select2 JavaScript。客户决定他们想要一个空间。如你所知,空间毁了一切,所以我们用下划线妥协,但我们想用下划线替换所有空格,以防不是每个人都遵循指示。 所以我添加了一些JavaScript,但是当我将新值保存到它们分配的属性时,select2中断,并且似乎是两行代码破坏了这个过程。

还有其他方法可以写这两行吗?

我的JavaScript(我会标记弄乱程序的那些))

<script>

    $("#tags").select2({
        placeholder: "Add Tag(s)...",
        tags: true
    });

    $('#tags').change(function() {
        var self = this;
            $(self).find('option').each(function() {
                var value = $(this).val();
                var text = $(this).text();
                var newValue = value.split(' ').join('_');
                var newText = text.split(' ').join('_');
                $(this).val(newValue); // This line overrides the tag manually input before it.
                $(this).text(newText);
                    $('.select2-selection__choice').each(function() {
                        var title = $(this).attr('title');
                        var newTitle = title.split(' ').join('_');
                        $(this).val(newTitle)
                        $(this).text(newTitle); //This line deletes the x in the tags
                    });
                });
            });
        });
</script>

1 个答案:

答案 0 :(得分:0)

如果您需要更改选择字段更改的文本和值,可以这样做:

$(function(){
  $('#tags').change(function() {
      $(this).find('option').each(function() {
          var value = $(this).val();
          var text = $(this).text();
          $(this).val(value.split(' ').join('_'))
          $(this).text(text.split(' ').join('_'))
      });
  });
});

这是plunkr demo

相关问题