简体   繁体   中英

Initialize Javascript Select2 controller using HTML5 data-* attributes

I'm trying to manage select2 library in order to augment the capabilities of natives select html controls.

According to the official documentation (very compressed) it says that for using select2 you only need to download they CSS and JavaScript files and that is (and also, implicitly assumed, that you need jQuery).

So, there is a way of initializing select using HTML5 data attributes , but I am not getting it; I'm trying to follow their example. Perhaps I am missing some important note here.

Here is the HTML I am trying to do

<!DOCTYPE html>
<html>

  <head>
      <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
      <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
      <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
  </head>

  <body>
    <h1>Hello Select2</h1>
  <div>
      <select multiple id="a_select" data-tags="true" data-placeholder="Select an option" data-allow-clear="true" style="width:100%">
        <option value="AL">Alabama</option>
        <option value="WY">Wyoming</option>
      </select>
  </div> 

  </body>

</html>

Also a link to plunker, to have a live example ready to go. https://plnkr.co/edit/Xk101K3sowAYQwbRCFez?p=preview

PS: I can achieve the desired result thought JavaScript, but is quite annoying to don't know what is not working when i just followed the example on the official site.

You're not initializing Select2 anywhere... data-* attributes let you override default configuration, but you still need to kick off the plugin:

<script>$('select').select2();</script>

https://plnkr.co/edit/RPObSPVl8jlZgtedsK38?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM