I am using select2 in an express app to make an input box where users can select subjects from a list.
The thing I'm struggling with is that select2
runs client-side, whereas any list I 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 this 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):
- 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 ajson
object, and update this object on tag creation - Seed the
<option>
from an external database (e.g. mongoose), and update this on tag creation
As far as I can work out, all of these options will 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.
My current approach is to specify a "local" json
file as my data source in my select2
call (see here) (however, using this approach doesn't seed the database with any options, so this isn't working).
I then check if each new tag exists in an array (dataBase
), and add it to the database if not:
// My initial database
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',
},
placeholder: 'Start typing to add subjects...',
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.
How can I modify this to load server-side data (json
or mongoose
document), and update this data with newly added options (that pass my tests)?
from Write new select2 option tags to local database in express
0 komentar:
Posting Komentar