Forked from waqasraza123/dynamically add new options if not exist in select2.js
Created
May 17, 2020 19:42
-
-
Save AndreiF13/0cb4701ba2ccf743353f6a62afe04279 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
keywords.select2({ | |
tags: true, | |
createTag: function (params) { | |
var term = $.trim(params.term); | |
var count = 0 | |
var existsVar = false; | |
//check if there is any option already | |
if($('#keywords option').length > 0){ | |
$('#keywords option').each(function(){ | |
if ($(this).text().toUpperCase() == term.toUpperCase()) { | |
existsVar = true | |
return false; | |
}else{ | |
existsVar = false | |
} | |
}); | |
if(existsVar){ | |
return null; | |
} | |
return { | |
id: params.term, | |
text: params.term, | |
newTag: true | |
} | |
} | |
//since select has 0 options, add new without comparing | |
else{ | |
return { | |
id: params.term, | |
text: params.term, | |
newTag: true | |
} | |
} | |
}, | |
maximumInputLength: 20, // only allow terms up to 20 characters long | |
closeOnSelect: true | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment