How to customize select2 prompt information-bububuko.com

Source: Internet
Author: User

Tags: Color Dom layui href default event replacement each ASE options

Recently, select2 has been used in the project to beautify and enrich the drop-down box functions. This plug-in features are rich and easy to use. You can transform the generated select tags, you can also directly generate a drop-down list for JSON data, including some retrieval and asynchronous loading functions, to meet visual and interactive requirements. It is a rare tool in the development process.

The official document is an English document and shows the configurable items in the form of a Q & A. The author may think this is more interesting, but for me, it must be a torment, now I want to share with you some questions about the development process:

1. Use Article 1. Configure the placeholder according to the prompts in the official documentation but it does not work;

1.1 you need to place an empty option tag in the select tag to store placeholder text;

1.2 you need to add a property "data-placeholder = 'placeholder'" to the select tag '"

1.3 Add the configuration item "Placeholder: Select" in the configuration item of select2 ',"

These things are not mentioned in the document. It's really tricky to hide so many tricks with a small function;

<! Doctype HTML> <HTML lang = "en"> View code2. cancel the search function of the drop-down box;

The configuration item is {minimumresultsforsearch: infinity ,}

Ii. Rebuild Article 1. confirmation in the selection process of the drop-down box

This type of event can be understood as the hook function of the select2 object in each stage of the operation. Of course, the relevant interface is officially configured for us, allowing us to select before opening, closing, and selecting, wait for the selected time to process the configured callback function;

This type of event (click to view) can be bound to the select2 instance on, and general functions can be processed in the callback function;

$ ("Select "). select2 ({placeholder: 'select '}). on ("select2: Selecting", function (e) {alert ("I selected ")});

Now there is a tricky problem. I need to prompt in the pop-up box at the moment of selection, and then do not allow other events of select2 to continue to execute, and then continue to execute again after confirmation in the pop-up box, in this case, the bullet box cannot be changed;

First, the Select drop-down box cannot be closed when you click the modal box:

We need to perform two steps:

1.1 after the pop-up box is displayed, the drop-down box cannot be closed unless you click "OK" or "cancel;

Select2 defines the close method on the prototype of its constructor baseselection. In the close method, the Custom Event is associated with the corresponding ID box. In this method, we can block the close operation;

Baseselection. prototype. _ attachclosehandler = function (container) {var self = This; $ (document. body ). on ('mousedown. select2. '+ container. ID, function (e) {var $ target = (e.tar get); var $ select = $ target. closest ('. select2 '); var $ all = $ ('. select2.select2-container -- open'); $ all. each (function () {var $ this = $ (this); If (this = $ select [0]) {return;} var $ element = $ this. data ('element'); // disable select2 when the modal box exists (here you can flexibly operate based on your class) vaR mask = $ (". layui-layer-shade "); If (mask. length = 0) {$ element. select2 ('close ');}});});};

  

1.2 When selecting content in the select2 box, the callback function cannot be executed immediately. The callback function must be placed in the "OK" button and click "post-processing;

In the initial program design, the correct method should be to design the subsequent functions in the layer validation callback function. I didn't intend to use the select2 plug-in, but you know the world of products, changes occur anytime, anywhere.

The initial function is triggered by monitoring the change status of the select tag. This is very important. If you want to put the target callback function into the select2 hook function, it will be executed directly, it does not meet the purpose of confirmation and cancellation in the pop-up box;

How to implement local asynchronous operations? In fact, we need to use an intermediate function to trigger the change event of the select tag.

VaR selectwebnamer = $ (". selectwebname "). select2 ({mymsg: 'site not configurable ', // This Is Not A select Configuration item. The following describes placeholder: 'Please select '}). on ("select2: Selecting", function (e) {If (data. sitelist. length = 0) {return false;} If (! That. Status. canchange) {that. _ confirmchange (E, that. _ queryparam, this );}});

First thing: block the default event. preventdefault (); our asynchronous functions are controlled by ourselves, and select2 cancels your own claims;

The function bound to the select2: Selecting event calls the dialog box;

That. _ queryparam is an intermediate function, which will be executed after the confirmation button; the next step will trigger the true select label change event;

The event is an event after select2 packaging. This encapsulated event allows us to track the select tag that really needs to be clicked. Therefore, we need to bring this event object into that. _ queryparam;

The select2 drop-down box should be closed at the moment of confirmation or unclicking, so it is also necessary to pass in this select2 object through correction;

_ Confirmchange: function (event, callback, $ this) {var that = This; event. preventdefault (); $ (". layui-layer-shade "). remove (); layer. closeall (); layer. open ({type: 1, title: 'return', Area: ['500px ', '270px'], BTN: ['confirmed', 'cancel'], closebtn: 2, content: $ ('# changemsg'), btn1: function (INDEX) {layer. closeall (); If (callback) {callback (event); $ ($ this ). select2 ('close'); That. status. canchange = true ;}}, btn2: function (INDEX) {layer. close (INDEX); $ ($ this ). select2 ('close ');}});//}},

The event object contains the DOM object for our current operation and the value on the selected option;

How does jquery select an option in select ?, I'm not using much of it. You may have forgotten it.

At this point, our change event is triggered, just like we manually click option, and the subsequent code can be executed smoothly.

  _queryParam:function(event){            if(!event){                return false;            }            var target = event.currentTarget;            var name  = event.params.args.data.text;            $(target).val(name).trigger("change");        },
Ii. How to modify the prompt information of select2

After select2 is used for instantiation, if no data is returned to us in the background, select2 will kindly prompt "no result is fonud" in the drop-down box (it seems like this)

Then, the cute interaction sister said, No, I don't want to read English, I don't know ..... Okay, you win.

After checking, it seems that there is no such prompt to configure the API, so I found select2.min IN THE introduced file. JS Ctrl + R ("no result is fonud" -------- "don't pull it, the background does not return ")

OK.

After a while, the interaction sister quit. Why are they all "don't pull it, the background didn't return"? What I want is "Haha, I don't want to return it to you ", "You were eaten by dinosaurs when you returned", "You are too ugly to show it to you ".......

Okay. I'll configure it for you.

After reading the document, the author provided the prompt information in 10 languages. In the past, there was a Chinese version of "Don't pull it, you didn't return it in the background ", there is also the English version of the "Don't blind pull la, then didn't give us", and the Japanese version of the "", hateful is the zh-CH.js and zh-TW.js are simplified and traditional, ah, let's get things done.

If you do not need to prompt different content, you can directly set the language in the configuration item to use the corresponding language;

If you want to prompt inappropriate content, you need to manually modify it to replace it.

Find the result module related to the result and find the append method on the prototype;

The field we use on option is mymsg to configure the content-free prompt in the drop-down box,

The original prompt condition is better to keep it for him. If I didn't configure the mymsg field, you should follow your original processing. If I have configured the mymsg field, you should follow my instructions.

If (data. Results = NULL | data. Results. Length = 0 )&&! Mymsg) {how do you handle it}

Else if (data. Results = NULL | data. Results. Length = 0 )&&!! Mymsg) {Add our information to the result: Message Time Parameter}

Results. prototype. append = function (data) {This. hideloading (); var mymsg = This. options. options. mymsg; // get the prompt text var $ Options = []; If (data. results = NULL | data. results. length = 0 )&&! Mymsg) {// press your if (this. $ results. children (). length = 0) {This. trigger ('ults: message', {message: 'noresults '}) ;}return;} else if (data. results = NULL | data. results. length = 0 )&&!! Mymsg) {// press my if (this. $ results. children (). length = 0) {This. trigger ('ults: message', {message: 'noresults ', mymessage: mymsg});} return;} data. results = This. sort (data. results); For (var d = 0; D <data. results. length; D ++) {var item = data. results [d]; var $ option = This. option (item); $ options. push ($ option);} This. $ results. append ($ options );};

Then, we can touch the displaymessage method from the results: Message event, and then we can judge whether "mymessage" has been brought. If yes, we will use our prompt.

Results. prototype. displaymessage = function (Params) {var escapemarkup = This. options. get ('escapemarkup'); this. clear (); this. hideloading (); vaR $ message = $ ('<li role = "treeitem" Aria-live = "assertive"' + 'class = "select2-results _ option"> </LI> '); vaR message = This. options. get ('translation '). get (Params. message); $ message. append (escapemarkup (Params. mymessage? Params. mymessage: Message (Params. ARGs) // determines whether to use our prompt or its own prompt. ); $ Message [0]. classname + = 'select2-results _ message'; this. $ results. append ($ message );};

 

So far, the interaction sister's needs have been met, and the transformation of select2 has ended.

 

How does select2 customize prompt information?

Tags: Color Dom layui href default event replacement each ASE options

Original article: http://www.cnblogs.com/wuhaozhou/p/7449661.html

VaR selectwebnamer = $ (". selectwebname "). select2 ({mymsg: 'site not configurable ', // This Is Not A select Configuration item. The following describes placeholder: 'Please select '}). on ("select2: Selecting", function (e) {If (data. sitelist. length = 0) {return false;} If (! That. Status. canchange) {that. _ confirmchange (E, that. _ queryparam, this );}});
Results. prototype. append = function (data) {This. hideloading (); var mymsg = This. options. options. mymsg; // get the prompt text var $ Options = []; If (data. results = NULL | data. results. length = 0 )&&! Mymsg) {// press your if (this. $ results. children (). length = 0) {This. trigger ('ults: message', {message: 'noresults '}) ;}return;} else if (data. results = NULL | data. results. length = 0 )&&!! Mymsg) {// press my if (this. $ results. children (). length = 0) {This. trigger ('ults: message', {message: 'noresults ', mymessage: mymsg});} return;} data. results = This. sort (data. results); For (var d = 0; D <data. results. length; D ++) {var item = data. results [d]; var $ option = This. option (item); $ options. push ($ option);} This. $ results. append ($ options );};

Then, we can touch the displaymessage method from the results: Message event, and then we can judge whether "mymessage" has been brought. If yes, we will use our prompt.

Results. prototype. displaymessage = function (Params) {var escapemarkup = This. options. get ('escapemarkup'); this. clear (); this. hideloading (); vaR $ message = $ ('<li role = "treeitem" Aria-live = "assertive"' + 'class = "select2-results _ option"> </LI> '); vaR message = This. options. get ('translation '). get (Params. message); $ message. append (escapemarkup (Params. mymessage? Params. mymessage: Message (Params. ARGs) // determines whether to use our prompt or its own prompt. ); $ Message [0]. classname + = 'select2-results _ message'; this. $ results. append ($ message );};

Else if (data. Results = NULL | data. Results. Length = 0 )&&!! Mymsg) {Add our information to the result: Message Time Parameter}

If (data. Results = NULL | data. Results. Length = 0 )&&! Mymsg) {how do you handle it}

The original prompt condition is better to keep it for him. If I didn't configure the mymsg field, you should follow your original processing. If I have configured the mymsg field, you should follow my instructions.

The field we use on option is mymsg to configure the content-free prompt in the drop-down box,

Find the result module related to the result and find the append method on the prototype;

If you want to prompt inappropriate content, you need to manually modify it to replace it.

If you do not need to prompt different content, you can directly set the language in the configuration item to use the corresponding language;

After reading the document, the author provided the prompt information in 10 languages. In the past, there was a Chinese version of "Don't pull it, you didn't return it in the background ", there is also the English version of the "Don't blind pull la, then didn't give us", and the Japanese version of the "", hateful is the zh-CH.js and zh-TW.js are simplified and traditional, ah, let's get things done.

Ii. How to modify the prompt information of select2

After select2 is used for instantiation, if no data is returned to us in the background, select2 will kindly prompt "no result is fonud" in the drop-down box (it seems like this)

  _queryParam:function(event){            if(!event){                return false;            }            var target = event.currentTarget;            var name  = event.params.args.data.text;            $(target).val(name).trigger("change");        },

At this point, our change event is triggered, just like we manually click option, and the subsequent code can be executed smoothly.

How does jquery select an option in select ?, I'm not using much of it. You may have forgotten it.

The event object contains the DOM object for our current operation and the value on the selected option;

_ Confirmchange: function (event, callback, $ this) {var that = This; event. preventdefault (); $ (". layui-layer-shade "). remove (); layer. closeall (); layer. open ({type: 1, title: 'return', Area: ['500px ', '270px'], BTN: ['confirmed', 'cancel'], closebtn: 2, content: $ ('# changemsg'), btn1: function (INDEX) {layer. closeall (); If (callback) {callback (event); $ ($ this ). select2 ('close'); That. status. canchange = true ;}}, btn2: function (INDEX) {layer. close (INDEX); $ ($ this ). select2 ('close ');}});//}},

The select2 drop-down box should be closed at the moment of confirmation or unclicking, so it is also necessary to pass in this select2 object through correction;

The event is an event after select2 packaging. This encapsulated event allows us to track the select tag that really needs to be clicked. Therefore, we need to bring this event object into that. _ queryparam;

That. _ queryparam is an intermediate function, which will be executed after the confirmation button; the next step will trigger the true select label change event;

The function bound to the select2: Selecting event calls the dialog box;

First thing: block the default event. preventdefault (); our asynchronous functions are controlled by ourselves, and select2 cancels your own claims;

How to implement local asynchronous operations? In fact, we need to use an intermediate function to trigger the change event of the select tag.

The initial function is triggered by monitoring the change status of the select tag. This is very important. If you want to put the target callback function into the select2 hook function, it will be executed directly, it does not meet the purpose of confirmation and cancellation in the pop-up box;

In the initial program design, the correct method should be to design the subsequent functions in the layer validation callback function. I didn't intend to use the select2 plug-in, but you know the world of products, changes occur anytime, anywhere.

1.2 When selecting content in the select2 box, the callback function cannot be executed immediately. The callback function must be placed in the "OK" button and click "post-processing;

Baseselection. prototype. _ attachclosehandler = function (container) {var self = This; $ (document. body ). on ('mousedown. select2. '+ container. ID, function (e) {var $ target = (e.tar get); var $ select = $ target. closest ('. select2 '); var $ all = $ ('. select2.select2-container -- open'); $ all. each (function () {var $ this = $ (this); If (this = $ select [0]) {return;} var $ element = $ this. data ('element'); // disable select2 when the modal box exists (here you can flexibly operate based on your class) vaR mask = $ (". layui-layer-shade "); If (mask. length = 0) {$ element. select2 ('close ');}});});};

Select2 defines the close method on the prototype of its constructor baseselection. In the close method, the Custom Event is associated with the corresponding ID box. In this method, we can block the close operation;

1.1 after the pop-up box is displayed, the drop-down box cannot be closed unless you click "OK" or "cancel;

We need to perform two steps:

First, the Select drop-down box cannot be closed when you click the modal box:

Now there is a tricky problem. I need to prompt in the pop-up box at the moment of selection, and then do not allow other events of select2 to continue to execute, and then continue to execute again after confirmation in the pop-up box, in this case, the bullet box cannot be changed;

$ ("Select "). select2 ({placeholder: 'select '}). on ("select2: Selecting", function (e) {alert ("I selected ")});

This type of event (click to view) can be bound to the select2 instance on, and general functions can be processed in the callback function;

This type of event can be understood as the hook function of the select2 object in each stage of the operation. Of course, the relevant interface is officially configured for us, allowing us to select before opening, closing, and selecting, wait for the selected time to process the configured callback function;

I. Select a dialog box in the drop-down box to confirm

How to customize select2 prompt information-bububuko.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.