A common requirement when using select2 plug-in is to add a 'tooltip' that will be visible when we hover the mouse over the selected element. This requirement is a must when we have some issues with width and a part of the selected element is not visible.
We can use these call-back functions for more advanced rendering too. Here in our example, we are rendering (displaying) both the result and the selection similarly. You can render them separately too if required. Refer to the 'Loading Remote Data' example in Select2 documentation . In that example, a remote request is made to rottentomatoes and 'formatResult' function is used to render result's (i.e movie's) poster thumbnail and synopsis. But the 'formatSelection' function is used to render just the movie's name in the Select2 .
Adding tooltip with this plug-in is cakewalk.(Once you find out how to do :) )
The select2 plug-in constructor has 2 call-back function parameters - formatSelection and formatResult that can be used to render the current selection and the result.
These methods can return either a HTML string, a DOM element, or a jQuery object that renders the selection. We can use these methods to return a 'div' element whose 'title' attribute is populated with the text. Actually by default select2 plug-in returns each selected element as a 'div'. It's just we are adding a 'title' attribute to it for adding tooltip. Below is an example. Add these 2 parameters in the select2 constructor :
formatResult: format, formatSelection: formatAnd then define the 'format' function like below outside the select2 constructor:
function format(item) { var originalText = item.text; return "<div title ='" + originalText + "'>" + originalText + "</div>"; }
We can use these call-back functions for more advanced rendering too. Here in our example, we are rendering (displaying) both the result and the selection similarly. You can render them separately too if required. Refer to the 'Loading Remote Data' example in Select2 documentation . In that example, a remote request is made to rottentomatoes and 'formatResult' function is used to render result's (i.e movie's) poster thumbnail and synopsis. But the 'formatSelection' function is used to render just the movie's name in the Select2 .
can you give me example?
ReplyDeleteuse my gist
ReplyDeletehttps://gist.github.com/m8rge/61929a6c356349bf080c
superb
ReplyDelete