Home Ask Login Register

Developers Planet

Your answer is one click away!

Calculating Machine February 2016

jquery select2: set tag length while creating the tag

Does anyone know how we can set the maximum number of lenght of a tag in select2. Below is my code and in this code i can create long tag (15-20). i want to restrict it to 10 char.

<script type="text/javascript">
var lastResults = [];

$("#tags").select2({
    multiple: true,

    //tags: true,    
    placeholder: "Please enter tags",
    tokenSeparators: [","],
    initSelection : function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({id: this, text: this});
        });
        callback(data);
    },
    ajax: {
        multiple: true,
        url: "fetch.php",
        dataType: "json",
        delay: 250,
        type: "POST",
      data: function(term,page) {
                        return {q: term};
                    },
                    results: function(data,page) {
                        return {results: data};
                    }, 

    },
    minimumInputLength: 2,
      // max tags is 3
    maximumSelectionSize: 3,   
    createSearchChoice: function (term) {
        var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
       // return { id: term, text: text };
         return {
            id: $.trim(term),
            text: $.trim(term) + ' (new tag)'
        };        
    },
});

$('#tags').on("change", function(e){
    if (e.added) {
        if (/ \(new\)$/.test(e.added.text)) {
           var response = confirm("Do you want to add the new tag "+e.added.id+"?");
           if (response == true) {
              alert("Will now send new tag to server: " + e.added.id);
              /*
               $.ajax({
                   type: "POST",
                   url: '/someurl&action=addTag',
                   data: {id: e.added.id, action: add},    
                   error: function () {
                      alert("error");
                   }
                });
               */
           } else {        

Answers


Kevin Brown February 2016

It sounds like you are looking for the maximumInputLength option. This will limit the length allowed for custom tags and when searching.

Post Status

Asked in February 2016
Viewed 2,698 times
Voted 11
Answered 1 times

Search




Leave an answer


Quote of the day: live life