LaraSell
3 months ago
196
0
General

change option data value in select2 ajax tags

Posted 3 months ago by LaraSell

I have this code for select2 tags method using ajax:

json data:

[
    {
        "id": "5",
        "text": "laravel3"
    },
    {
        "id": "4",
        "text": "laravel2"
    }
]

code:


$(document).ready(function(){
      $('#tag_list').select2({
          placeholder: "Choose tags...",
          tags: true,
          minimumInputLength: 3,
          tokenSeparators: [",", " "],

          createSearchChoice: function(term, data) {
              if ($(data).filter(function() {
                  return this.text.localeCompare(term) === 0;
              }).length === 0) {
                  return {
                      id: term,
                      text: term
                  };
              }
          },
          ajax: {
              url: '/tags/find',
              dataType: 'json',
              data: function (params) {
                  return {
                      q: $.trim(params.term)
                  };
              },
              processResults: function (data) {
                  return {
                      results: data
                  };
              },
              delay: 250,
              cache: true
          }
      });
  });

with my code i can search and selected data from database or add new tag to my select2 area. now when i select data from database, <option value""> is data id but when i add new tag <option value""> is name(text) like this:

Now I need to change option value(database) from data id to data name(text). how do change option data value from id to name?!

Please sign in or create an account to participate in this conversation.