select2 | jQuery based replacement for select boxes | Plugin library

 by   select2 JavaScript Version: 4.1.0-rc.0 License: MIT

kandi X-RAY | select2 Summary

select2 is a JavaScript library typically used in Plugin, jQuery applications. select2 has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can install using 'npm i sog-select2' or download it from GitHub, npm.
Select2 is a jQuery-based replacement for select boxes. It supports searching, remote data sets, and pagination of results. To get started, checkout examples and documentation at
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        select2 has a medium active ecosystem.
                        summary
                        It has 25541 star(s) with 6376 fork(s). There are 729 watchers for this library.
                        summary
                        It had no major release in the last 12 months.
                        summary
                        There are 71 open issues and 4670 have been closed. On average issues are closed in 267 days. There are 19 open pull requests and 0 closed requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of select2 is 4.1.0-rc.0
                        select2 Support
                          Best in #Plugin
                            Average in #Plugin
                            select2 Support
                              Best in #Plugin
                                Average in #Plugin

                                  kandi-Quality Quality

                                    summary
                                    select2 has 0 bugs and 0 code smells.
                                    select2 Quality
                                      Best in #Plugin
                                        Average in #Plugin
                                        select2 Quality
                                          Best in #Plugin
                                            Average in #Plugin

                                              kandi-Security Security

                                                summary
                                                select2 has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                select2 code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                select2 Security
                                                  Best in #Plugin
                                                    Average in #Plugin
                                                    select2 Security
                                                      Best in #Plugin
                                                        Average in #Plugin

                                                          kandi-License License

                                                            summary
                                                            select2 is licensed under the MIT License. This license is Permissive.
                                                            summary
                                                            Permissive licenses have the least restrictions, and you can use them in most projects.
                                                            select2 License
                                                              Best in #Plugin
                                                                Average in #Plugin
                                                                select2 License
                                                                  Best in #Plugin
                                                                    Average in #Plugin

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        select2 releases are available to install and integrate.
                                                                        summary
                                                                        Deployable package is available in npm.
                                                                        summary
                                                                        select2 saves you 6674 person hours of effort in developing the same functionality from scratch.
                                                                        summary
                                                                        It has 14458 lines of code, 37 functions and 409 files.
                                                                        summary
                                                                        It has high code complexity. Code complexity directly impacts maintainability of the code.
                                                                        select2 Reuse
                                                                          Best in #Plugin
                                                                            Average in #Plugin
                                                                            select2 Reuse
                                                                              Best in #Plugin
                                                                                Average in #Plugin
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi has reviewed select2 and discovered the below as its top functions. This is intended to give you an instant insight into select2 implemented functionality, and help decide if they suit your requirements.
                                                                                  • The mousewheel event handler
                                                                                    • Normalizes a name to be replaced .
                                                                                      • Calculate scroll bar width
                                                                                        • Create a require function that calls the module .
                                                                                          • Returns the fallback message for an action .
                                                                                            • call this module
                                                                                              • An ending - like function .
                                                                                                • Helper function to adjust the size of the old event
                                                                                                  • Split name into namespace .
                                                                                                    • Adjust the next scroll bar to account for scrollbar
                                                                                                      Get all kandi verified functions for this library.
                                                                                                      Get all kandi verified functions for this library.

                                                                                                      select2 Key Features

                                                                                                      Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

                                                                                                      select2 Examples and Code Snippets

                                                                                                      No Code Snippets are available at this moment for select2.
                                                                                                      Community Discussions

                                                                                                      Trending Discussions on select2

                                                                                                      JQuery - Hide/show option from previous selected dropdown
                                                                                                      chevron right
                                                                                                      Bootstrap, Select2, The jQuery replacement for select boxes, limit results
                                                                                                      chevron right
                                                                                                      AJAX data in template of Select2
                                                                                                      chevron right
                                                                                                      Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (93)
                                                                                                      chevron right
                                                                                                      wordpress script_loader_tag in function.php
                                                                                                      chevron right
                                                                                                      Populate preselected values to Select2
                                                                                                      chevron right
                                                                                                      How to display exact value from drop down?
                                                                                                      chevron right
                                                                                                      Dropdown selected option changes color and a gap between the container and search-box
                                                                                                      chevron right
                                                                                                      Display a specific div depending on value generated after submit
                                                                                                      chevron right
                                                                                                      Cant create tags on rails with Select2
                                                                                                      chevron right

                                                                                                      QUESTION

                                                                                                      JQuery - Hide/show option from previous selected dropdown
                                                                                                      Asked 2022-Apr-16 at 18:45

                                                                                                      I want to hide option from previous selected dropdown but my solution only works for two dropdown list.

                                                                                                      This means that when I come to third dropdown list it will not display selected option from second dropdown list which is ok but it will display selected option from first one.

                                                                                                      So, as I understand, methods I'm using overrides the last one that's why it not works.

                                                                                                      Here is my select lists:

                                                                                                      
                                                                                                          
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                          
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                          
                                                                                                      
                                                                                                      

                                                                                                      And my script: strong text

                                                                                                      function getSelectValue(select1) {
                                                                                                                  $("#select2 option[value='" + select1 + "']").hide();
                                                                                                                  $("#select2 option[value!='" + select1 + "']").show();
                                                                                                                  $("#select3 option[value='" + select1 + "']").hide();
                                                                                                                  $("#select3 option[value!='" + select1 + "']").show();
                                                                                                      
                                                                                                          }
                                                                                                      
                                                                                                          function getSelectValue2(select2) {
                                                                                                              
                                                                                                                  $("#select1 option[value='" + select2 + "']").hide();
                                                                                                                  $("#select1 option[value!='" + select2 + "']").show();
                                                                                                                  $("#select3 option[value='" + select2 + "']").hide();
                                                                                                                  $("#select3 option[value!='" + select2 + "']").show();
                                                                                                      
                                                                                                          }
                                                                                                      
                                                                                                          function getSelectValue3(select3) {
                                                                                                              $("#select1 option[value='" + select3 + "']").hide();
                                                                                                              $("#select1 option[value!='" + select3 + "']").show();
                                                                                                              $("#select2 option[value='" + select3 + "']").hide();
                                                                                                              $("#select2 option[value!='" + select3 + "']").show();
                                                                                                      
                                                                                                              
                                                                                                          }
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2022-Apr-16 at 18:45

                                                                                                      I created a single function that handles unhiding and hiding of all options, then filters the other dropdowns' options based on all selected values. Here's the function/demo:

                                                                                                      function hideOthers() {
                                                                                                        // Get all selected values
                                                                                                        let selectedValues = $(".form-control option:selected").map(function() {
                                                                                                          if (this.value.length === 0) {
                                                                                                            return null;
                                                                                                          }
                                                                                                          return this.value;
                                                                                                        });
                                                                                                        // Unhide all so we can hide the correct ones
                                                                                                        $("select.form-control option").removeAttr('hidden');
                                                                                                      
                                                                                                        // Filter out the selected values from dropdowns
                                                                                                        $(".form-control").each(function() {
                                                                                                          var selectElem = $(this);
                                                                                                          $.each(selectedValues, function(index, value) {
                                                                                                            // If the selected value from the array is from the applicable , skip hiding
                                                                                                            if (selectElem.find("option:selected").val() !== value) {
                                                                                                              selectElem.find(`option[value="${value}"]`).attr('hidden', true);
                                                                                                            }
                                                                                                          });
                                                                                                        });
                                                                                                      }
                                                                                                      
                                                                                                      
                                                                                                        
                                                                                                        1
                                                                                                        2
                                                                                                        3
                                                                                                        4
                                                                                                        5
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                        
                                                                                                        1
                                                                                                        2
                                                                                                        3
                                                                                                        4
                                                                                                        5
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                        
                                                                                                        1
                                                                                                        2
                                                                                                        3
                                                                                                        4
                                                                                                        5
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/71894061

                                                                                                      QUESTION

                                                                                                      Bootstrap, Select2, The jQuery replacement for select boxes, limit results
                                                                                                      Asked 2022-Mar-08 at 16:07

                                                                                                      On client side (there is no server side) we have html file with javascript which we are open in browser. In HTML file we include bootstrap and select2 plugins to create UI interface and we include one file with data which have more than 10 000 rows. This is part of basic.html file:

                                                                                                      ....
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      ...
                                                                                                      

                                                                                                      This is part of mydata.js file:

                                                                                                      var mydata = [{id: 0, text: "aa"}, ..... ...... {id: 10000, text: "aa 10000"}];
                                                                                                      

                                                                                                      Question: Because variable mydata is very big, we have bad responsive time when we are selecting data. How can we restrict Select2 plugin to initially select only 10 rows on begining (initially when we load the script) and every time when trying to find some data? On the other words, results for showing must be limited.

                                                                                                      There are no server side, no ajax, no (my)sql server, no any other programing language, only html, javascript and bootstrap5 with select2 plugin.

                                                                                                      ANSWER

                                                                                                      Answered 2022-Mar-04 at 12:52

                                                                                                      If the problem come from the generation of the select by select2, i don't really see a solution. for me, you can replace select2 element by a autocomplete input text w3school (I tested it with some autogenerated data, 200 000 object to be exact, wit hsame structure as you and it's not too bad)

                                                                                                      Source https://stackoverflow.com/questions/71349239

                                                                                                      QUESTION

                                                                                                      AJAX data in template of Select2
                                                                                                      Asked 2022-Jan-20 at 18:03

                                                                                                      I am populating Select2 with AJAX data. My code is like below.

                                                                                                          function formatState(state) {
                                                                                                              if (!state.id) { return state.text; }
                                                                                                              var output = $('');   // I would like get data `text[1]` of `processResults` here.
                                                                                                              return output;
                                                                                                          };
                                                                                                      
                                                                                                          //more code here
                                                                                                      
                                                                                                          cellEle.html(``);
                                                                                                          
                                                                                                          let selectEle = cellEle.children("select").select2({
                                                                                                      
                                                                                                              //more code here
                                                                                                              
                                                                                                              ajax: {
                                                                                                      
                                                                                                                  //more code here
                                                                                                      
                                                                                                                  processResults: function (data) {                
                                                                                                                      var options = [];
                                                                                                                      if (data) {
                                                                                                                          $.each(data, function (index, text) {
                                                                                                                              options.push({ id: index, text: text[0]});
                                                                                                                          });
                                                                                                                      }
                                                                                                                      return {
                                                                                                                          results: options,
                                                                                                                          more: false
                                                                                                                      };
                                                                                                                  },
                                                                                                              },
                                                                                                              templateSelection: formatState,
                                                                                                          });
                                                                                                      

                                                                                                      I would like get AJAX data text[1] of processResults inside formatState() of templateSelection.

                                                                                                      How can I get it ?

                                                                                                      ANSWER

                                                                                                      Answered 2022-Jan-20 at 18:03

                                                                                                      You can pass any extra data via processResults. In your case it can be

                                                                                                      var options = [];
                                                                                                      if (data) {
                                                                                                        $.each(data.items, function (index, text) {
                                                                                                          options.push({ id: index, text: text[0], text2: text[1] /* <-- extra data */});
                                                                                                        });
                                                                                                      }
                                                                                                      return {
                                                                                                        results: options,
                                                                                                        more: false
                                                                                                      };
                                                                                                      

                                                                                                      Then access it in templateSelection

                                                                                                      if (!state.id) {
                                                                                                        return state.text;
                                                                                                      }
                                                                                                      return $(`${state.text} & ${state.text2}`);
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/70784804

                                                                                                      QUESTION

                                                                                                      Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (93)
                                                                                                      Asked 2022-Jan-12 at 23:22

                                                                                                      Getting below error after installed latest node.js (v16.13.1)

                                                                                                      Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (93) For more information on which environments are supported please see: https://github.com/sass/node-sass/releases/tag/v4.14.1 I have created static pages for my application and use sass and gulp

                                                                                                      I have a static pages and using Sass in the page and use gulp to run on the browser.(npm install). Below are the version which worked my application:

                                                                                                      • Node.js - 12.18.0
                                                                                                      • gulp - "4.0.2"
                                                                                                      • "gulp-sass": "4.1.0"

                                                                                                      Package.json file

                                                                                                      "scripts": {
                                                                                                                    "start": "gulp watch"
                                                                                                          },
                                                                                                      "dependencies": {
                                                                                                              "@fortawesome/fontawesome-free": "5.15.1",
                                                                                                              "@ttskch/select2-bootstrap4-theme": "^1.5.2",
                                                                                                              "bootstrap": "4.5.3",
                                                                                                              "bootstrap-datepicker": "^1.9.0",
                                                                                                              "jquery": "3.5.1",
                                                                                                              "jquery.easing": "^1.4.1",
                                                                                                              "select2": "^4.1.0-rc.0",
                                                                                                              "gulp": "4.0.2"
                                                                                                          },
                                                                                                          "devDependencies": {
                                                                                                              "browser-sync": "2.26.13",
                                                                                                              "del": "6.0.0",
                                                                                                              "gulp": "4.0.2",
                                                                                                              "gulp-autoprefixer": "7.0.1",
                                                                                                              "gulp-clean-css": "4.3.0",
                                                                                                              "gulp-header": "2.0.9",
                                                                                                              "gulp-plumber": "^1.2.1",
                                                                                                              "gulp-rename": "2.0.0",
                                                                                                              "gulp-sass": "4.1.0",
                                                                                                              "gulp-uglify": "3.0.2",
                                                                                                              "merge-stream": "2.0.0"
                                                                                                          }
                                                                                                      

                                                                                                      Even using command npm rebuild node-sass is not changing anything.

                                                                                                      ANSWER

                                                                                                      Answered 2022-Jan-12 at 23:22

                                                                                                      gulp-sass 4.1.0 uses node-sass 4, and node-sass 4 does not support Node.js 16, as indicated in this table.

                                                                                                      To support Node.js 16, upgrade gulp-sass: the latest version today is 5.1.0:

                                                                                                      npm install -D gulp-sass@5.1.0
                                                                                                      

                                                                                                      This will give you node-sass 7, which supports all current versions of Node.js, including Node.js 16.

                                                                                                      Source https://stackoverflow.com/questions/70676490

                                                                                                      QUESTION

                                                                                                      wordpress script_loader_tag in function.php
                                                                                                      Asked 2022-Jan-12 at 19:21

                                                                                                      I am trying to add defer and async to my script tags to increase it is performance

                                                                                                      here is the code that I am using

                                                                                                      function add_defer_attribute($tag, $handle) {
                                                                                                          print('hi');
                                                                                                          echo('hi');
                                                                                                      
                                                                                                         // add script handles to the array below
                                                                                                         $scripts_to_defer = array('jquery-core-js','fortuna.lib-js');
                                                                                                         
                                                                                                         foreach($scripts_to_defer as $defer_script) {
                                                                                                             
                                                                                                            if ($defer_script === $handle) {
                                                                                                               return str_replace(' src', ' defer="defer" src', $tag);
                                                                                                            }
                                                                                                         }
                                                                                                         return $tag;
                                                                                                      }
                                                                                                      
                                                                                                      add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);
                                                                                                      
                                                                                                      function add_async_attribute($tag, $handle) {
                                                                                                          print('hello');
                                                                                                          echo('hello');
                                                                                                         // add script handles to the array below
                                                                                                         $scripts_to_async = array('jquery-core-js', 'fortuna.lib-js');
                                                                                                         
                                                                                                         foreach($scripts_to_async as $async_script) {
                                                                                                            if ($async_script === $handle) {
                                                                                                               return str_replace(' src', ' async="async" src', $tag);
                                                                                                            }
                                                                                                         }
                                                                                                         return $tag;
                                                                                                      }
                                                                                                      
                                                                                                      add_filter('script_loader_tag', 'add_async_attribute', 10, 2);
                                                                                                      

                                                                                                      I added this code at the bottom of function.php that is found in the theme that I am using

                                                                                                      but it does not work, I have added the id of the scripts that I need to defer and async

                                                                                                      nothing happen, can anyone advise what should I do

                                                                                                      here are the script tags on my site

                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2022-Jan-12 at 19:21

                                                                                                      Replace

                                                                                                      $scripts_to_defer = array('jquery-core-js','fortuna.lib-js');
                                                                                                      

                                                                                                      With this

                                                                                                      $scripts_to_defer = array( 'jquery-core', 'fortuna.lib' );
                                                                                                      

                                                                                                      You don't need to add -js to handle because WordPress automatically adds when enqueue scripts Try the below code.

                                                                                                      function add_defer_attribute( $tag, $handle ) {
                                                                                                          // add script handles to the array below
                                                                                                          $scripts_to_defer = array( 'jquery-core','fortuna.lib' );
                                                                                                          foreach( $scripts_to_defer as $defer_script ) {
                                                                                                              if ($defer_script === $handle) {
                                                                                                                  return str_replace( ' src', ' defer="defer" src', $tag );
                                                                                                              }
                                                                                                          }
                                                                                                          return $tag;
                                                                                                      }
                                                                                                      add_filter( 'script_loader_tag', 'add_defer_attribute', 10, 2 );
                                                                                                      
                                                                                                      function add_async_attribute( $tag, $handle ) {
                                                                                                          // add script handles to the array below
                                                                                                          $scripts_to_async = array( 'jquery-core', 'fortuna.lib' );
                                                                                                          foreach( $scripts_to_async as $async_script ) {
                                                                                                              if ($async_script === $handle) {
                                                                                                                  return str_replace( ' src', ' async="async" src', $tag );
                                                                                                              }
                                                                                                          }
                                                                                                          return $tag;
                                                                                                      }
                                                                                                      add_filter( 'script_loader_tag', 'add_async_attribute', 10, 2 );
                                                                                                      

                                                                                                      Tested and working fine.

                                                                                                      Source https://stackoverflow.com/questions/70685964

                                                                                                      QUESTION

                                                                                                      Populate preselected values to Select2
                                                                                                      Asked 2022-Jan-04 at 21:01

                                                                                                      I am trying to populate some preselected values to Select2. My code is like below.

                                                                                                      (function($) {  
                                                                                                        $(document).ready(function() {
                                                                                                          $(".volunteer").on("click", function (event) {
                                                                                                      
                                                                                                            let element_id = event.target.id;
                                                                                                            // Check if select is already loaded
                                                                                                            if (!$(this).has("select").length) {
                                                                                                              var cellEle = $(this);
                                                                                                      
                                                                                                              // Populate select element
                                                                                                              cellEle.html(``);
                                                                                                      
                                                                                                              // Initialise select2
                                                                                                              let selectEle = cellEle.children("select").select2({
                                                                                                                allowClear: true,
                                                                                                                maximumSelectionLength: 3,
                                                                                                                ajax: {
                                                                                                                  url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
                                                                                                                  dataType: 'json',
                                                                                                                  data: function (params) {
                                                                                                                    return { 
                                                                                                                              action: 'get_data',
                                                                                                                          };
                                                                                                                  },
                                                                                                                  type: "post",
                                                                                                                  processResults: function (data) { 
                                                                                                                    var options = [];
                                                                                                                    if ( data ) {
                                                                                                                      $.each( data, function( index, text ) {
                                                                                                                        options.push({ id: index, text: text });
                                                                                                                      });
                                                                                                                    }
                                                                                                                    return {
                                                                                                                      results: options
                                                                                                                    };
                                                                                                                  }
                                                                                                                }
                                                                                                              });
                                                                                                      
                                                                                                              selectEle.select2('open');
                                                                                                      
                                                                                                              $.ajax({
                                                                                                                type: "POST",
                                                                                                                dataType: 'json',
                                                                                                                url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
                                                                                                                data: { 
                                                                                                                  element_id: element_id,
                                                                                                                  action: 'get_preselect_values',
                                                                                                                },
                                                                                                                success: function (data) {
                                                                                                                  var options = [];
                                                                                                                    
                                                                                                                  if (data) {
                                                                                                                    $.each( data, function( index, text ) {
                                                                                                                      options.push({ id: index, text: text });
                                                                                                                    });
                                                                                                                  }
                                                                                                                  
                                                                                                                  selectEle.val(options).trigger('change'); // I am trying to attach value here. But it is not working. 
                                                                                                                }
                                                                                                              });
                                                                                                      
                                                                                                      
                                                                                                              selectEle.on('select2:select', function () {
                                                                                                                $.ajax({
                                                                                                                  type: "POST",
                                                                                                                  dataType: 'jsonp',
                                                                                                                  url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
                                                                                                                  data: { 
                                                                                                                    selected_items: selectEle.val(),
                                                                                                                    element_id: element_id,
                                                                                                                    action: 'save_data'
                                                                                                                  }
                                                                                                                });
                                                                                                              });
                                                                                                      
                                                                                                              selectEle.on("select2:unselecting", function () {
                                                                                                                $.ajax({
                                                                                                                  type: "POST",
                                                                                                                  dataType: 'jsonp',
                                                                                                                  url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
                                                                                                                  data: { 
                                                                                                                    selected_items: selectEle.val(),
                                                                                                                    task_id: element_id,
                                                                                                                    action: 'save_data'
                                                                                                                  } 
                                                                                                                });
                                                                                                              }).trigger('change');
                                                                                                            }
                                                                                                          });
                                                                                                        });
                                                                                                      })(jQuery)
                                                                                                      

                                                                                                      I am trying to attach values but it is not working.

                                                                                                      I am trying to something like this.

                                                                                                      ANSWER

                                                                                                      Answered 2022-Jan-04 at 21:01

                                                                                                      The options should be appended to the select element rather than selected with .val(). Details on this can be found in the documetation here.

                                                                                                      An updated snippet of the code to .append the preselected values:

                                                                                                      $.ajax({
                                                                                                        type: "POST",
                                                                                                        dataType: "json",
                                                                                                        url: "url",
                                                                                                        data: {
                                                                                                          element_id: element_id,
                                                                                                          action: "get_preselect_values",
                                                                                                        },
                                                                                                        success: function (data) {              
                                                                                                          if (data) {
                                                                                                            $.each( data, function( index, text ) {                
                                                                                                              // Declare a new Option for the value - Note id is set to text
                                                                                                              const option = new Option(text, text, true, true);
                                                                                                              // Append the value to the select element
                                                                                                              selectEle.append(option).trigger('change');
                                                                                                            });
                                                                                                          }
                                                                                                        }
                                                                                                      });
                                                                                                      

                                                                                                      Please note the id of the preselected values must match the id of the retrieved list of values. The id in the question is the index of the item in the array, whcih won't match the preselected index. If these values don't match you'll be able to select preselected items twice.

                                                                                                      To ensure the values match you could update your code to set the id to the same string as the text. This would need to be done when adding values options.push({ id: text, text: text });. It must also be done when preselecting values as per the example above new Option(text, text, true, true); where text is passed as both the text and value of the Option.

                                                                                                      Additionally you may wish to load the already selected values before initailising select2, otherwise the values may appear after select2 has opened which could cause unexpected behaviour.

                                                                                                      Source https://stackoverflow.com/questions/70573541

                                                                                                      QUESTION

                                                                                                      How to display exact value from drop down?
                                                                                                      Asked 2021-Dec-29 at 12:31

                                                                                                      I have configured my select via select2 and things works quite well.

                                                                                                      I have used templateResult with formatState approach to add the icon to my dropdown options.

                                                                                                      $(".js-country-list").select2({
                                                                                                        templateResult: formatState
                                                                                                      });
                                                                                                      

                                                                                                      that however does not change anything to selected value (see image below).

                                                                                                      How can I make sure that selected value (in my case EUR) would be displayed exactly same as option: Euro (EUR)?

                                                                                                      Thanks.

                                                                                                      ANSWER

                                                                                                      Answered 2021-Dec-29 at 12:31

                                                                                                      The templateSelection method described at https://select2.org/selections can be used to achieve this, it can be passed the same function used by templateResult.

                                                                                                      $(".js-country-list").select2({
                                                                                                        templateResult: formatState,
                                                                                                        templateSelection: formatState
                                                                                                      });
                                                                                                      

                                                                                                      Example listing countries and their flags (not currencies) is incorporated below.

                                                                                                      // Template function which adds CSS flag and displays country name
                                                                                                      function flagTemplate(country){
                                                                                                        return $("" + country.text + "");
                                                                                                      }
                                                                                                      
                                                                                                      // Generate correct URL based on entered search term
                                                                                                      function generateUrl(params){
                                                                                                        if(params.term){
                                                                                                          return "https://restcountries.com/v3.1/name/" + params.term;
                                                                                                        } else {
                                                                                                          return "https://restcountries.com/v3.1/all";
                                                                                                        }
                                                                                                      }
                                                                                                      
                                                                                                      // Initialise select2 using flagTemplate function for both result and selection
                                                                                                      $('#countrySelect').select2({
                                                                                                        // Set template for results and selection
                                                                                                        templateResult: flagTemplate,
                                                                                                        templateSelection: flagTemplate,
                                                                                                        // Set placeholder text
                                                                                                        placeholder: 'Select country...',
                                                                                                        // Load country list from https://restcountries.com
                                                                                                        ajax: {
                                                                                                          url: generateUrl,
                                                                                                          cache: 250,
                                                                                                          dataType: "json",
                                                                                                          processResults: function(data) {      
                                                                                                            return {
                                                                                                              results: data
                                                                                                                .map(x => ({id: x.cca2.toLowerCase(), text: x.name.common}))
                                                                                                                .sort((a, b) => ('' + a.text).localeCompare(b.text))
                                                                                                            };
                                                                                                          }
                                                                                                        }
                                                                                                      });
                                                                                                      #countrySelect {
                                                                                                        width: 300px;
                                                                                                      }
                                                                                                      
                                                                                                      .flag-text {
                                                                                                        margin-left: 10px;
                                                                                                      }
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/70341757

                                                                                                      QUESTION

                                                                                                      Dropdown selected option changes color and a gap between the container and search-box
                                                                                                      Asked 2021-Dec-19 at 17:03

                                                                                                      I was able to change the background color of the selected option but it changes its color after I have hovered over any other option.

                                                                                                      Is there a way to control this and how can I get rid of this annoying space between the results search-box and container even though it doesnt appear in the code snippet.

                                                                                                      The code

                                                                                                      #bap + .select2 .select2-selection__rendered {
                                                                                                        background-color: yellow;
                                                                                                      }
                                                                                                      
                                                                                                      /* Each result */
                                                                                                      #select2-bap-results {
                                                                                                        background-color: salmon;
                                                                                                      }
                                                                                                      
                                                                                                      /* Higlighted (hover) result */
                                                                                                      #select2-bap-results .select2-results__option--highlighted {
                                                                                                        background-color: rgb(5, 27, 27) !important;
                                                                                                      }
                                                                                                      
                                                                                                      /* Selected option */
                                                                                                      #select2-bap-results .select2-results__option[aria-selected="true"] {
                                                                                                        background-color: rgb(13, 14, 14) !important;
                                                                                                      }
                                                                                                      
                                                                                                      /* Around the search field */
                                                                                                      .select2-search {
                                                                                                        background-color: orange;
                                                                                                      }
                                                                                                      
                                                                                                      /* Search field */
                                                                                                      .select2-search input {
                                                                                                        background-color: pink;
                                                                                                      }
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                        
                                                                                                        
                                                                                                        
                                                                                                      
                                                                                                      
                                                                                                        
                                                                                                        
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                        
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                          
                                                                                                              Alabama
                                                                                                              Wyoming
                                                                                                              Wyoming
                                                                                                              Wyoming
                                                                                                          
                                                                                                       
                                                                                                      
                                                                                                      
                                                                                                       
                                                                                                       
                                                                                                       

                                                                                                      Solution for the annoying "blank space"
                                                                                                      Added more line height to the element
                                                                                                      #bap + .select2 .select2-selection__rendered {}

                                                                                                      ANSWER

                                                                                                      Answered 2021-Dec-19 at 16:43

                                                                                                      You can add this CSS to change the selected option background color that appears with the gray background: (I simply used green for the example)

                                                                                                      #select2-bap-results .select2-results__option--selected {
                                                                                                          background-color: green;
                                                                                                      }
                                                                                                      

                                                                                                      That change applied to the runnable example below:

                                                                                                      #bap + .select2 .select2-selection__rendered {
                                                                                                        background-color: yellow;
                                                                                                      }
                                                                                                      
                                                                                                      /* Each result */
                                                                                                      #select2-bap-results {
                                                                                                        background-color: salmon;
                                                                                                      }
                                                                                                      
                                                                                                      /* Higlighted (hover) result */
                                                                                                      #select2-bap-results .select2-results__option--highlighted {
                                                                                                        background-color: rgb(5, 27, 27) !important;
                                                                                                      }
                                                                                                      
                                                                                                      /* Selected option */
                                                                                                      #select2-bap-results .select2-results__option[aria-selected="true"] {
                                                                                                        background-color: rgb(13, 14, 14) !important;
                                                                                                      }
                                                                                                      
                                                                                                      /* Around the search field */
                                                                                                      .select2-search {
                                                                                                        background-color: orange;
                                                                                                      }
                                                                                                      
                                                                                                      /* Search field */
                                                                                                      .select2-search input {
                                                                                                        background-color: pink;
                                                                                                      }
                                                                                                      
                                                                                                      #select2-bap-results .select2-results__option--selected {
                                                                                                          background-color: green;
                                                                                                      }
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                        
                                                                                                        
                                                                                                        
                                                                                                      
                                                                                                      
                                                                                                        
                                                                                                        
                                                                                                        
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                          
                                                                                                              Alabama
                                                                                                              Wyoming
                                                                                                              Wyoming
                                                                                                              Wyoming
                                                                                                          
                                                                                                       
                                                                                                      
                                                                                                      
                                                                                                       
                                                                                                       
                                                                                                       

                                                                                                      Source https://stackoverflow.com/questions/70407485

                                                                                                      QUESTION

                                                                                                      Display a specific div depending on value generated after submit
                                                                                                      Asked 2021-Dec-11 at 01:13

                                                                                                      I am setting up a questioner for some of my students and i am stuck.

                                                                                                      I have several questions i need to ask my students. All the questions being yes/no questions being selected from a dropdown. "No" will always remain 0 but "Yes" will have a figure somewhere between 0-100 for each question. I am trying to add those selected values to sum them to a total so i can display a score/result.

                                                                                                      I have attached the HTML and JS to sum the values from each of the dropdowns (All fine until here).

                                                                                                      function submit() { let total=0; document.querySelectorAll('select').forEach(element => { total += parseInt(element.value); }); console.log(total); }
                                                                                                      
                                                                                                      
                                                                                                      console.log = function(message) {
                                                                                                      document.getElementById('result').innerHTML = message;};
                                                                                                      console.log('');
                                                                                                       
                                                                                                       

                                                                                                      1. Did you attend summer training? NO YES

                                                                                                      2. Have you passed all your grades? NO YES

                                                                                                      3. Have you completed summer assignments? NO YES

                                                                                                      Submit

                                                                                                      My final hurdle is depending on the end result 'that is when i hit submit' i want to show a specific div with some text on it right below the result/score for each score range (ie any result between 0-20,20-40,40-60,60-100). So for example if the result falls between 20-30. I want to show up a specific div below the result which will have some explainer text on it and the rest of the divs for each score range be hidden.

                                                                                                      I am not well versed in JS and would appreciate some help or guidance. I have added my code for reference

                                                                                                      ANSWER

                                                                                                      Answered 2021-Dec-10 at 20:34

                                                                                                      If you want to pre-define the text in html you could do so like this:

                                                                                                      HTML

                                                                                                      some text
                                                                                                      some text
                                                                                                      some text
                                                                                                      some text
                                                                                                      

                                                                                                      CSS:

                                                                                                      .hidden { display: none; }
                                                                                                      

                                                                                                      then you just remove the class "hidden" from the desired target, with JS:

                                                                                                      document.getElementById("40-60").classList.remove("hidden")
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/70310021

                                                                                                      QUESTION

                                                                                                      Cant create tags on rails with Select2
                                                                                                      Asked 2021-Nov-19 at 09:32

                                                                                                      I make autocomplete tags on rails with Select2.js Client and rails code perfectly works, if tags exsist. But if I want to create or add new tag it breaks. I can create tags, but it still makes error, along ids I get new named. but I can't change params

                                                                                                      document.addEventListener('turbolinks:load', selectTags)
                                                                                                      
                                                                                                      $(document).ready(selectTags)
                                                                                                      
                                                                                                      function selectTags() {
                                                                                                        $('#post_tag_ids').select2({
                                                                                                            createTag: function (params) {
                                                                                                              return {
                                                                                                                id: $.trim(params.term) + '#(new)',
                                                                                                                text: $.trim(params.term)
                                                                                                              }
                                                                                                          },
                                                                                                          ajax: {
                                                                                                              url: '/tags/search',
                                                                                                              dataType: 'json',
                                                                                                              delay: 200,
                                                                                                              data: function (params) {
                                                                                                                return {
                                                                                                                  q: params.term
                                                                                                                }
                                                                                                              },
                                                                                                              processResults: function (data, params) {
                                                                                                                  data.map(v => {v.text = v.name})
                                                                                                                return {
                                                                                                                  results: data
                                                                                                              }
                                                                                                              },
                                                                                                                cache: true
                                                                                                              },
                                                                                                              tags: true,
                                                                                                            minimumInputLength: 2,
                                                                                                            maximumInputLength: 20
                                                                                                          })
                                                                                                      }
                                                                                                      

                                                                                                      Simple Post (tags owner) controller:

                                                                                                        def create
                                                                                                          @post = Post.new(post_params)
                                                                                                          set_post_defaults
                                                                                                      
                                                                                                          respond_to do |format|
                                                                                                            if @post.save
                                                                                                              format.html { redirect_to @post, notice: "Post was successfully created." }
                                                                                                              format.json { render :show, status: :created, location: @post }
                                                                                                            else
                                                                                                              format.html { render :new, status: :unprocessable_entity }
                                                                                                              format.json { render json: @post.errors, status: :unprocessable_entity }
                                                                                                            end
                                                                                                          end
                                                                                                        end
                                                                                                      
                                                                                                        def post_params
                                                                                                          params.require(:post).permit(:category_id, :title, :content, :tag_list, :tag, { tag_ids: [] }, :tag_ids)
                                                                                                        end
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2021-Nov-19 at 09:32

                                                                                                      My current decision

                                                                                                      before_action :create_new_tags, only: [:create, :update]
                                                                                                      .
                                                                                                      .
                                                                                                      .
                                                                                                        def create_new_tags
                                                                                                          key = "#(new)"
                                                                                                          tag_ids = []
                                                                                                          params[:post][:tag_ids].each_with_index do |tag_id, index|
                                                                                                            next if tag_id.empty?
                                                                                                            if tag_id.include?(key) then
                                                                                                              tag = Tag.find_or_create_by(name: tag_id.sub(key, ""))
                                                                                                              tag.save if !tag.id
                                                                                                            else  
                                                                                                              tag = Tag.find(tag_id.to_i)
                                                                                                            end  
                                                                                                            tag_ids << tag.id.to_s
                                                                                                          end  
                                                                                                          params[:post][:tag_ids] = tag_ids
                                                                                                        end 
                                                                                                      

                                                                                                      .... and after small refactoring for rubocop:

                                                                                                        def create_new_tags
                                                                                                          params[:post][:tag_ids].each_with_index do |tag_id, index|
                                                                                                            next unless tag_id.include?("#(new)")
                                                                                                      
                                                                                                            tag = Tag.find_or_create_by(name: tag_id.sub("#(new)", ""))
                                                                                                            tag.save unless tag.id
                                                                                                            params[:post][:tag_ids][index] = tag.id.to_s
                                                                                                          end
                                                                                                        end
                                                                                                      

                                                                                                      Actual version here

                                                                                                      Source https://stackoverflow.com/questions/69691745

                                                                                                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                                      Vulnerabilities

                                                                                                      No vulnerabilities reported

                                                                                                      Install select2

                                                                                                      You can install using 'npm i sog-select2' or download it from GitHub, npm.

                                                                                                      Support

                                                                                                      The documentation for Select2 is available [online at the documentation website][documentation] and is located within the [docs directory of this repository][documentation-directory].
                                                                                                      Find more information at:
                                                                                                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                                      Find more libraries
                                                                                                      Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                                      Save this library and start creating your kit

                                                                                                      Share this Page

                                                                                                      share link

                                                                                                      Explore Related Topics

                                                                                                      Consider Popular Plugin Libraries

                                                                                                      jquery

                                                                                                      by jquery

                                                                                                      select2

                                                                                                      by select2

                                                                                                      YouCompleteMe

                                                                                                      by ycm-core

                                                                                                      telegraf

                                                                                                      by influxdata

                                                                                                      Try Top Libraries by select2

                                                                                                      docs

                                                                                                      by select2CSS

                                                                                                      select2.github.io

                                                                                                      by select2HTML

                                                                                                      Compare Plugin Libraries with Highest Support

                                                                                                      jsonschema2pojo

                                                                                                      by joelittlejohn

                                                                                                      telegraf

                                                                                                      by influxdata

                                                                                                      select2

                                                                                                      by select2

                                                                                                      jquery

                                                                                                      by jquery

                                                                                                      audacity

                                                                                                      by audacity

                                                                                                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                                      Find more libraries
                                                                                                      Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                                      Save this library and start creating your kit