Different display value for selecte text using select2.js

后端 未结 5 2131
闹比i
闹比i 2021-01-18 15:24

Trying to implement a custom select dropdown using select2 plugin Is it possible to have the selected value to display only the actual option \'value\' instead of the text,

5条回答
  •  醉话见心
    2021-01-18 15:58

    Even tough this question has been here for a while and probably overcome, I had the same doubt and I think I should share what I've got.

    @Spokey answer is very good, and works. However it only works if you are making a simple selection. If you want to make a multiple selection box, thing will get a bit more difficult, as Select2 does not provide any unique attribute to easily find each option selected.

    Reading @HyperLink answer, I changed the way of thinking and finally got an working result. It would be kind of hard if you really want to pass just the value to be shown, I've wasted a couple of hours trying to do that. But having a new approach like this, things gets easier:

    
    

    Just added what the value is on the real text, which will probably not make a big difference to the user, but for us, it will help a lot. The main difference of the other answer javascript, is the change(function(){}):

    change(function () {
     var options = $('.select2-search-choice > div');
     i = 1;
     Array.prototype.forEach.call(options, function(o) {
         o.id = 'choice'+i;                // optional, creating ids to
         i++;                              // find it easily if you want
    
         aux = o.textContent.split(" - "); // Divide value from text
         o.textContent = aux[0];           // Get first part, i.e, value
         console.log(aux);
     })
    

    Try it here

提交回复
热议问题