jQuery select2 editable with dynamic data

Your Javascript code:

EmpType.getList(function(response){
            $scope.empTypes=response.data;
            var typesArr = new Array();
            for (var int = 0; int <$scope.empTypes.length; int++) {
                var jsonObj = {
                        "id": $scope.empTypes[int].id,
                        "text": $scope.empTypes[int].name
                };
                typesArr[int] = jsonObj;
            }
           
            $("#empTypes").select2({
                createSearchChoice:function(term, data) {
                    if ($(data).filter(function() {
                        return this.text.localeCompare(term)===0;
                    }).length===0)
                    {return {id:term, text:term};}
                },
                data:typesArr
            });
           
        });
 
Your HTML code:
 

<input type="text" name="empTypes" id="empTypes"
                    class="form-control" />
 
and don't forget to include below files:
 
    <link rel="stylesheet" href="css/select2.css" />
    <link rel="stylesheet" href="css/select2-bootstrap.css"/> 
    <script type="text/javascript" src="lib/select2.min.js"></script>

No comments:

Post a Comment