将新的select2选项标签写入express中的本地数据库 [英] Write new select2 option tags to local database in express

查看:144
本文介绍了将新的select2选项标签写入express中的本地数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在快递应用中使用 select2 来创建一个输入框,用户可以从列表中选择主题,并且可以使用任何新添加的选项更新此列表

I am using select2 in an express app to make an input box where users can select subjects from a list, and can update this list with any newly added options.

我正在努力的是 select2 运行客户端,而我用来播种我的< option> 标签(我想要添加新选项)的任何数据都是服务器端。

The thing I'm struggling with is that select2 runs client-side, whereas any data I use to seed my <option> tags (that I want to append new options to) is server-side.

我希望用户能够添加原始列表中不存在的主题,以便为将来的用户提供新添加的选项(以及原始的那些)

I want users to be able to add subjects that don't exist in the original list, so that future users will be presented with newly added options (as well as the original ones)

这些是我为实现这一目标而考虑的选项(增加满意度):

These are the options I've considered for achieving this (in increasing desirability):


  • 为每个添加的标记添加新的<选项>主题< / option> html标记

  • 将新标签推送到数组,并从此数组中播种< option> s

  • json 对象中种植< option> ,并在标记创建时更新此对象

  • 从外部数据库中种植< option> (例如mongoose),并在标签创建时更新此内容

  • Add new <option>Subject</option> html tags for each added tag
  • Push new tags to an array, and seed the <option>s from this array
  • Seed the <option> from a json object, and update this object on tag creation
  • Seed the <option> from an external database (e.g. mongoose), and update this on tag creation

据我所知,所有这些选项都需要我的客户端代码( select2-js )与服务器端代码(我的数组, .json 文件或<$ c $)对话c> mongoose 架构会是),而我不知道如何去做这个

As far as I can see, all of these options require that my client-side code (select2-js) talks to server-side code (where my array, .json file or mongoose schema would be), and I have no idea how to go about doing this.

在我目前的方法中,我试图在我的数据源中指定一个本地 json 文件 select2 致电(见此处)。但是,这并没有使用任何选项为数据库设定种子,因此这不符合我的预期。

In my current approach I am attempting to to specify a "local" json file as my data source in my select2 call (see here). However, this doesn't seed the database with any options, so this isn't working as I expected.

然后我检查一个数组中是否存在每个新标记( dataBase ),并将其添加到数据库中不是:

I then check if each new tag exists in an array (dataBase), and add it to the database if not:

// Data to seed initial tags:
var dataBase = [
    { id: 0, text: 'Maths'},
    { id: 1, text: 'English'},
    { id: 2, text: 'Biology'},
    { id: 3, text: 'Chemistry'},
    { id: 4, text: 'Geography'}
];


$(document).ready(function() {
    $('.select2-container').select2({
        ajax: {
            url: '../../subjects.json',
            dataType: 'json',
        },
        width: 'style',
        multiple: true,
        tags: true,
        createTag: function (tag) {
            var isNew = false;
            tag.term = tag.term.toLowerCase();
            console.log(tag.term);
            if(!search(tag.term, dataBase)){
                if(confirm("Are you sure you want to add this tag:" + tag.term)){
                    dataBase.push({id:dataBase.length+1, text: tag.term});
                    isNew = true;
                }
            }
            return {
                        id: tag.term,
                        text: tag.term,
                        isNew : isNew
                    };
        },
        tokenSeparators: [',', '.']
    })
});

// Is tag in database?
function search(nameKey, myArray){
    for (var i=0; i < myArray.length; i++) {
        if (myArray[i].text.toLowerCase() === nameKey.toLowerCase()) {
            return true
        }
    }
    return false
};

但是,这种方法会将新标签添加到刷新页面后销毁的数组中,并且不存储新标签。

However, this approach will add the new tags to an array that is destroyed once I refresh the page, and new tags are not stored.

如何修改此标签以加载服务器端数据( json mongoose 文档或其他任何被认为是最佳实践的方法),并使用新添加的选项(通过我的测试)更新此数据?

How can I modify this to load server-side data (json, mongoose document or anything else that is considered a best practice), and update this data with newly added options (that pass my tests)?

推荐答案

您可以使用 select2:select select2:取消选择事件。

var dataBase = [{
    id: 0,
    text: 'Maths'
  },
  {
    id: 1,
    text: 'English'
  },
  {
    id: 2,
    text: 'Biology'
  },
  {
    id: 3,
    text: 'Chemistry'
  },
  {
    id: 4,
    text: 'Geography'
  }
];

$(document).ready(function() {
  $('.select2-container').select2({
    data: dataBase,
    placeholder: 'Start typing to add subjects...',
    width: 'style',
    multiple: true,
    tags: true,
    createTag: function(tag) {
      return {
        id: tag.term,
        text: tag.term,
        isNew: true
      };
    },
    tokenSeparators: [',', '.']
  })
  $(document).on("select2:select select2:unselect", '.select2-container', function(e) {
    var allSelected = $('.select2-container').val();
    console.log('All selected ' + allSelected);

    var lastModified = e.params.data.id;
    console.log('Last Modified ' + lastModified);

    var dbIdArray = dataBase.map((i) => i.id.toString());
    var allTagged = $('.select2-container').val().filter((i) => !(dbIdArray.indexOf(i) > -1))
    console.log('All Tagged ' + allTagged);
  });
});

.select2-container {
  width: 200px;
}

<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.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

<select class="select2-container"></select>

这篇关于将新的select2选项标签写入express中的本地数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆