Thursday, April 14, 2016

How to add custom callback to jquery plugin

Leave a Comment

I would like to add a custom function to Select2 plugin (but I don't have the necessary knowledge), like

$('.select2').select2({     optionDrawCallback : function(li_element){         return li_element.className += 'bg-'+li_element.text;     } }); 

Then I went to source code (select2.full.js) and found where each option element is created, which is here:

Results.prototype.option = function (data) {...} 

But now I can't find out how to trigger my function. I was able to trigger it over the dataAdapter, which should be the select itself, but that's not what I need.

Any suggestion would be very appreciated.

2 Answers

Answers 1

Updated answer:

You should consider avoiding getting into the code of a 3rd party library and changing it, since your change will be overridden in a future versions (assuming you get them), and you'll have to figure out again where to put it in.

Look into the Templating option in the docs.

Here is an example of how to achieve what you ask for.

var data = [{    id: 0,    text: 'gray'  }, {    id: 1,    text: 'green'  }, {    id: 2,    text: 'blue'  }, {    id: 3,    text: 'yellow'  }, {    id: 4,    text: 'red'  }];    function formatState(state) {    var $state = $('<div class="bg-' + state.text + '" style="background-color: ' + state.text + ';" > ' + state.text + '</div>')    return $state;  };    $('.select2').select2({    data: data,    templateResult: formatState  });
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>  <select class="select2">  </select>

Here it is in a JsFiddle if you will: https://jsfiddle.net/yq70y8cy/1/

Old answer:

You should consider avoiding getting into the code of a 3rd party library and changing it, since your change will be overridden in a future versions (assuming you get them), and you'll have to figure out again where to put it in.

Instead, try keeping it simple, by using regular jQuery / javascript code, e.g:

$('.select2 li').each(function(index){    var $this = $(this);    $this.addClass('bg-' + $this.text()); }) 

Answers 2

I added a callback using on jquery function for click event of class select2 which shows the default/selected option. This works fine as far as markup structure for select2 will remain the same. Please refer this fiddle for demo.

$('.select2').on('click', function(li_element){     $(this).siblings(".select2-container--open").find(".select2-results__option").each(function(index,el) {         console.log($(el).text());         $(el).addClass('bg-' + $(el).text());     }); }); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment