In our previous example we saw how to integrate select2 plug-in with remote data retrieved in JSON format. As per the bare bones select2 options we used till now, we can select only options available from the remote data query output. What if we want to include a new choice on the fly? For this we have to include the createSearchChoice call-back function while invoking the select2's constructor.
Below is an extract from select2's documentation for 'createSearchChoice':
Creates a new selectable choice from user's search term. Allows creation of choices not available via the query function. Useful when the user can create choices on the fly, eg for the 'tagging' usecase.
After adding the 'createSearchChoice' call-back function to our example, we can select new students like Robert, Stephen etc as shown in the below screenshot even though they are not part of the JSON response received from the remote call.
Below is an extract from select2's documentation for 'createSearchChoice':
Creates a new selectable choice from user's search term. Allows creation of choices not available via the query function. Useful when the user can create choices on the fly, eg for the 'tagging' usecase.
createSearchChoice : createNewSelectItem,And then define the function like below outside the select2 constructor:
function createNewSelectItem(term,data) { if ($(data).filter (function() {return this.text.localeCompare(term)===0;}).length===0) { return { id:term, text:term }; } }If a new choice is created it is displayed first in the selection list so that user may select it by simply pressing enter.
After adding the 'createSearchChoice' call-back function to our example, we can select new students like Robert, Stephen etc as shown in the below screenshot even though they are not part of the JSON response received from the remote call.
No comments:
Post a Comment