Select2.js drop-down box usage summary, select2.js drop-down box

Source: Internet
Author: User

Select2.js drop-down box usage summary, select2.js drop-down box

After using the Select2 plug-in for so long, you should also write an article to sum up. At the beginning, I felt that Select2 was not particularly useful, but I couldn't find a better drop-down box plug-in than Select2.

In my opinion, Select2 has two versions, the latest version has some new features, and the method parameters are updated, which is better than the original version. This article focuses on the new version.

Official Website: http://select2.github.io/

Demo:

The blog system can only demonstrate simple functions.

A. file is imported into select2.full.js?select2.min.css (version 4.0.1) and jquery.1.8.3 and later.

If the latest version of select2 references a lower version of jquery, some functions cannot be used normally. For example, allowClear: true

Use the latest version<Select> </select>Tag (you can use input for localized data, but select must be used for ajax Remote Data)

2. placeholder

Placeholder prompt text. If you need a clear function, you must set placeholder.

3. Load local data

The default data attribute of select2 is id and text. The new version can be customized, but the default data attribute is better. Therefore, it is best to convert the json format to id and text. Of course, you can add other attributes.

Var data = [{id: 0, text: 'enhancement '}, {id: 1, text: 'bug'}, {id: 2, text: 'duplicate '}, {id: 3, text: 'invalid' },{ id: 4, text: 'wontfix'}]; $ ("# c01-select "). select2 ({data: data, placeholder: 'select ', allowClear: true })

4. Load Remote Data

$("#c01-select").select2({ ajax: { url: "data.json", dataType: 'json', delay: 250, data: function (params) {  return {  q: params.term,  }; }, processResults: function (data) {  return {  results: data  }; }, cache: true }, escapeMarkup: function (markup) { return markup; },  minimumInputLength: 1, templateResult: formatRepo,  templateSelection: formatRepoSelection });

Note:

1. q: params. term query parameters (params. term indicates the content in the input box, and the parameter name that q occurs to the server. You can add custom parameters here, such as stype: 'person ')

2. results In processResults: data is returned (the final data is returned to results. If my data is under data. res, data. res is returned. This is related to the json returned by the server)

3. minimumInputLength: the minimum number of characters required for query. maximumSelectionLength related to it indicates the maximum input limit.

4. escapeMarkup character escape Processing

5. templateResult returned result callback function formatRepo (repo) {return repo. text} to display the text of the returned result to the drop-down box. Of course, you can return repo. text + "1 ";

6. The selected templateSelection callback function formatRepoSelection (repo) {return repo. text}

7. for the returned json format, the default json format of select2 is [{id: 1, text: 'text'}, {id: 2, text: 'text'}]. the new version strictly requires this format. Of course you can add columns, such as [{id: 1, text: 'text', name: 'liu'}]

5. Obtain the selected items

Var res = $ ("# c01-select "). select2 ("data") [0]; // single choice var reslist = $ ("# c01-select "). select2 ("data"); // select multiple if (res = undefined) {alert ("You have not selected any items");} if (reslist. length) {alert ("any item you selected ");}

6. Clear selected items and set unavailable

// Clear the selection $ ("# c01-select "). val (null ). trigger ("change"); $ ("# c01-select "). val ("Your placeholder "). trigger ("change"); // if you are using an input tag (local data by default), you can use $ ("# c01-select "). val (''); To clear options // disabled $ (" # c01-select "). prop ("disabled", false); // available $ ("# c01-select "). prop ("disabled", true); // unavailable

7. enable multiple choice

$("#c01-select").select2({ data:data, multiple: true});

Multiple choice Demonstration:

8. Comparison between the new version and the old version

1. Result callback and selected callback names: formatResult, formatSelection (old version), templateResult, and templateSelection (new version)

2. Initialization:

// Old version. Note that if there is no value (empty) in the text box during initialization, the method initSelection: function (element, callback) {var id = $ (element) will not be triggered ). val (); var data = {id: id, text: id}; // The initialized data here. You can obtain the data from the server by using the id (ajax ), then load it into the callback (data);} // new version, directly add option $ ("# id") to select "). append (new Option ("Jquery", 10001, false, true); // or $ ("# id "). append ("<option value = '000000'> Jquery </option> ");

3. Get or set the value: select2 ("val") (old version); $ ("select"). val () (new version)

Recommended

Var res = $ ("# id "). select2 ("data"); // returns an array. If you select one option, res [0] is obtained. If you do not enter the array, you can obtain the id and text attributes, for example, res [0]. names

4. disable or enable: $ ("select "). enable (false); (old version); $ ("select "). prop ("disabled", true); (new version)

5. theme style: the new style has been updated. To use the old style, you can set theme: "classic"

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.