How can I dynamically resize a select2 input to be the same width as the selected option?select2 - Setting different width to input and dropdownSelect2 JQuery Select Boxes insert text optionSelect2 on hidden input on Modal does not have proper widthDynamically edit option in select2How to pass <option> attributes to select2?jQuery select2 dynamic optionsselect2 (v4.0.2) dynamically change options and selectionsValidation not working on jquery.steps with more than one select2 select inputGet the value of selected option in select2 and then set the value to an input text using jquery?Select2 plugin: Showing selected options outside the form element

Creating a character, is Noble a class or a background?

How to honestly answer questions from a girlfriend like "How did you find this place" without giving the impression I'm always talking about my exes?

pgfkeys: .store in constructed macro

What to look for in climbing shoes?

What do mathematicians mean when they say some conjecture can’t be proven using the current technology?

In special relativity is mass just a measure of all other energy than kinetic?

Why does the Trade Federation become so alarmed upon learning the ambassadors are Jedi Knights?

Why did Steve Rogers choose Sam in Endgame?

What alternatives exist to at-will employment?

What is this old "lemon-squeezer" shaped pan

Cauchy reals and Dedekind reals satisfy "the same mathematical theorems"

If a player tries to persuade somebody, what should that creature roll not to be persuaded?

Source of story about the Vilna Gaon and immigration policy

Doing research in academia and not liking competition

Teferi's Time Twist on creature with +1/+1 counter

Credit card stolen every 1-2 years. What am I doing wrong?

What are the arguments for California’s nonpartisan blanket (jungle) primaries?

Why limit to revolvers?

Why doesn't philosophy have higher standards for its arguments?

Too many spies!

Using two linked programs, output ordinal numbers up to n

Why does FFmpeg choose 10+20+20 ms instead of an even 16 ms for 60 fps GIF images?

Index Uniqueness Overhead

What's the phrasal verb for carbonated drinks exploding out of the can after being shaken?



How can I dynamically resize a select2 input to be the same width as the selected option?


select2 - Setting different width to input and dropdownSelect2 JQuery Select Boxes insert text optionSelect2 on hidden input on Modal does not have proper widthDynamically edit option in select2How to pass <option> attributes to select2?jQuery select2 dynamic optionsselect2 (v4.0.2) dynamically change options and selectionsValidation not working on jquery.steps with more than one select2 select inputGet the value of selected option in select2 and then set the value to an input text using jquery?Select2 plugin: Showing selected options outside the form element






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















I'm building a 'natural language' search form using a series of inline select inputs, using jQuery Select2 for styling. The widths of the Select2 inputs appear to be set to the width of the selected option on initialisation, which is great. I just can't work out how to get the width to update when the selected option is changed. Any ideas?



Many thanks!










share|improve this question




























    4















    I'm building a 'natural language' search form using a series of inline select inputs, using jQuery Select2 for styling. The widths of the Select2 inputs appear to be set to the width of the selected option on initialisation, which is great. I just can't work out how to get the width to update when the selected option is changed. Any ideas?



    Many thanks!










    share|improve this question
























      4












      4








      4








      I'm building a 'natural language' search form using a series of inline select inputs, using jQuery Select2 for styling. The widths of the Select2 inputs appear to be set to the width of the selected option on initialisation, which is great. I just can't work out how to get the width to update when the selected option is changed. Any ideas?



      Many thanks!










      share|improve this question














      I'm building a 'natural language' search form using a series of inline select inputs, using jQuery Select2 for styling. The widths of the Select2 inputs appear to be set to the width of the selected option on initialisation, which is great. I just can't work out how to get the width to update when the selected option is changed. Any ideas?



      Many thanks!







      jquery-select2 select2






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jun 21 '16 at 11:54









      Matt SimsMatt Sims

      1503 silver badges11 bronze badges




      1503 silver badges11 bronze badges






















          4 Answers
          4






          active

          oldest

          votes


















          15














          Try to add this to yor CSS file:



          .select2-container 
          width: 100% !important;



          It solved my resize problems with select2



          (Edited: I do not use placeholders)






          share|improve this answer




















          • 1





            its set only container width, but if you have placeholder - it will by cut

            – Lukas Pierce
            Nov 10 '17 at 9:40






          • 1





            this one fixes Bootstap 3 issues

            – qwertzman
            Jan 30 '18 at 10:41











          • not working for me

            – Asheeka K P
            Sep 17 '18 at 11:19


















          2














          You can use window resize function.



          Example:



          // Fix select2 width
          $(window).on('resize', function()
          $('.form-group').each(function()
          var formGroup = $(this),
          formgroupWidth = formGroup.outerWidth();

          formGroup.find('.select2-container').css('width', formgroupWidth);

          );
          );


          Live - https://jsfiddle.net/Lwy6qnwy/






          share|improve this answer























          • Thanks, but not quite what I was trying to do – I needed it to resize when changing the selected option, not on window resize. In the end I couldn't find a working solution so didn't use Select2.

            – Matt Sims
            Jan 20 '17 at 9:57


















          1














          Just had to do something like this for a site



          $(e).on("select2:closing", function(e) 
          if (e.hasOwnProperty('params') &&
          e.params.hasOwnProperty('args') &&
          e.params.args.hasOwnProperty('originalEvent') &&
          e.params.args.originalEvent.hasOwnProperty('target'))
          var newWidth = $(e.params.args.originalEvent.target).width();
          var id = $(e.params.args.originalEvent.target).attr('id');
          var container = $("span[aria-labelledby=""+id.split("-result")[0]+"-container"+""]");
          $(container).parents('span.select2').width(newWidth + 21);

          );


          This is probably not fool-proof and is tied to the current API. But it gets the width of the element in the dropdown before the dropdown closes and then applies that to the container.



          One thing of note, you may need to float the dropdown items to get their real size.



          .select2-results__option 
          float: left;
          clear: both;






          share|improve this answer






























            0














            $('.select2-search__field').attr('style','width:auto');

            $('.select2-search__field[placeholder=""]').attr('style','width:10px');





            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37943730%2fhow-can-i-dynamically-resize-a-select2-input-to-be-the-same-width-as-the-selecte%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              15














              Try to add this to yor CSS file:



              .select2-container 
              width: 100% !important;



              It solved my resize problems with select2



              (Edited: I do not use placeholders)






              share|improve this answer




















              • 1





                its set only container width, but if you have placeholder - it will by cut

                – Lukas Pierce
                Nov 10 '17 at 9:40






              • 1





                this one fixes Bootstap 3 issues

                – qwertzman
                Jan 30 '18 at 10:41











              • not working for me

                – Asheeka K P
                Sep 17 '18 at 11:19















              15














              Try to add this to yor CSS file:



              .select2-container 
              width: 100% !important;



              It solved my resize problems with select2



              (Edited: I do not use placeholders)






              share|improve this answer




















              • 1





                its set only container width, but if you have placeholder - it will by cut

                – Lukas Pierce
                Nov 10 '17 at 9:40






              • 1





                this one fixes Bootstap 3 issues

                – qwertzman
                Jan 30 '18 at 10:41











              • not working for me

                – Asheeka K P
                Sep 17 '18 at 11:19













              15












              15








              15







              Try to add this to yor CSS file:



              .select2-container 
              width: 100% !important;



              It solved my resize problems with select2



              (Edited: I do not use placeholders)






              share|improve this answer















              Try to add this to yor CSS file:



              .select2-container 
              width: 100% !important;



              It solved my resize problems with select2



              (Edited: I do not use placeholders)







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 10 '17 at 14:14

























              answered Aug 2 '16 at 9:57









              NMCNMC

              5004 silver badges12 bronze badges




              5004 silver badges12 bronze badges







              • 1





                its set only container width, but if you have placeholder - it will by cut

                – Lukas Pierce
                Nov 10 '17 at 9:40






              • 1





                this one fixes Bootstap 3 issues

                – qwertzman
                Jan 30 '18 at 10:41











              • not working for me

                – Asheeka K P
                Sep 17 '18 at 11:19












              • 1





                its set only container width, but if you have placeholder - it will by cut

                – Lukas Pierce
                Nov 10 '17 at 9:40






              • 1





                this one fixes Bootstap 3 issues

                – qwertzman
                Jan 30 '18 at 10:41











              • not working for me

                – Asheeka K P
                Sep 17 '18 at 11:19







              1




              1





              its set only container width, but if you have placeholder - it will by cut

              – Lukas Pierce
              Nov 10 '17 at 9:40





              its set only container width, but if you have placeholder - it will by cut

              – Lukas Pierce
              Nov 10 '17 at 9:40




              1




              1





              this one fixes Bootstap 3 issues

              – qwertzman
              Jan 30 '18 at 10:41





              this one fixes Bootstap 3 issues

              – qwertzman
              Jan 30 '18 at 10:41













              not working for me

              – Asheeka K P
              Sep 17 '18 at 11:19





              not working for me

              – Asheeka K P
              Sep 17 '18 at 11:19













              2














              You can use window resize function.



              Example:



              // Fix select2 width
              $(window).on('resize', function()
              $('.form-group').each(function()
              var formGroup = $(this),
              formgroupWidth = formGroup.outerWidth();

              formGroup.find('.select2-container').css('width', formgroupWidth);

              );
              );


              Live - https://jsfiddle.net/Lwy6qnwy/






              share|improve this answer























              • Thanks, but not quite what I was trying to do – I needed it to resize when changing the selected option, not on window resize. In the end I couldn't find a working solution so didn't use Select2.

                – Matt Sims
                Jan 20 '17 at 9:57















              2














              You can use window resize function.



              Example:



              // Fix select2 width
              $(window).on('resize', function()
              $('.form-group').each(function()
              var formGroup = $(this),
              formgroupWidth = formGroup.outerWidth();

              formGroup.find('.select2-container').css('width', formgroupWidth);

              );
              );


              Live - https://jsfiddle.net/Lwy6qnwy/






              share|improve this answer























              • Thanks, but not quite what I was trying to do – I needed it to resize when changing the selected option, not on window resize. In the end I couldn't find a working solution so didn't use Select2.

                – Matt Sims
                Jan 20 '17 at 9:57













              2












              2








              2







              You can use window resize function.



              Example:



              // Fix select2 width
              $(window).on('resize', function()
              $('.form-group').each(function()
              var formGroup = $(this),
              formgroupWidth = formGroup.outerWidth();

              formGroup.find('.select2-container').css('width', formgroupWidth);

              );
              );


              Live - https://jsfiddle.net/Lwy6qnwy/






              share|improve this answer













              You can use window resize function.



              Example:



              // Fix select2 width
              $(window).on('resize', function()
              $('.form-group').each(function()
              var formGroup = $(this),
              formgroupWidth = formGroup.outerWidth();

              formGroup.find('.select2-container').css('width', formgroupWidth);

              );
              );


              Live - https://jsfiddle.net/Lwy6qnwy/







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 23 '16 at 1:18









              MichaelMichael

              715 bronze badges




              715 bronze badges












              • Thanks, but not quite what I was trying to do – I needed it to resize when changing the selected option, not on window resize. In the end I couldn't find a working solution so didn't use Select2.

                – Matt Sims
                Jan 20 '17 at 9:57

















              • Thanks, but not quite what I was trying to do – I needed it to resize when changing the selected option, not on window resize. In the end I couldn't find a working solution so didn't use Select2.

                – Matt Sims
                Jan 20 '17 at 9:57
















              Thanks, but not quite what I was trying to do – I needed it to resize when changing the selected option, not on window resize. In the end I couldn't find a working solution so didn't use Select2.

              – Matt Sims
              Jan 20 '17 at 9:57





              Thanks, but not quite what I was trying to do – I needed it to resize when changing the selected option, not on window resize. In the end I couldn't find a working solution so didn't use Select2.

              – Matt Sims
              Jan 20 '17 at 9:57











              1














              Just had to do something like this for a site



              $(e).on("select2:closing", function(e) 
              if (e.hasOwnProperty('params') &&
              e.params.hasOwnProperty('args') &&
              e.params.args.hasOwnProperty('originalEvent') &&
              e.params.args.originalEvent.hasOwnProperty('target'))
              var newWidth = $(e.params.args.originalEvent.target).width();
              var id = $(e.params.args.originalEvent.target).attr('id');
              var container = $("span[aria-labelledby=""+id.split("-result")[0]+"-container"+""]");
              $(container).parents('span.select2').width(newWidth + 21);

              );


              This is probably not fool-proof and is tied to the current API. But it gets the width of the element in the dropdown before the dropdown closes and then applies that to the container.



              One thing of note, you may need to float the dropdown items to get their real size.



              .select2-results__option 
              float: left;
              clear: both;






              share|improve this answer



























                1














                Just had to do something like this for a site



                $(e).on("select2:closing", function(e) 
                if (e.hasOwnProperty('params') &&
                e.params.hasOwnProperty('args') &&
                e.params.args.hasOwnProperty('originalEvent') &&
                e.params.args.originalEvent.hasOwnProperty('target'))
                var newWidth = $(e.params.args.originalEvent.target).width();
                var id = $(e.params.args.originalEvent.target).attr('id');
                var container = $("span[aria-labelledby=""+id.split("-result")[0]+"-container"+""]");
                $(container).parents('span.select2').width(newWidth + 21);

                );


                This is probably not fool-proof and is tied to the current API. But it gets the width of the element in the dropdown before the dropdown closes and then applies that to the container.



                One thing of note, you may need to float the dropdown items to get their real size.



                .select2-results__option 
                float: left;
                clear: both;






                share|improve this answer

























                  1












                  1








                  1







                  Just had to do something like this for a site



                  $(e).on("select2:closing", function(e) 
                  if (e.hasOwnProperty('params') &&
                  e.params.hasOwnProperty('args') &&
                  e.params.args.hasOwnProperty('originalEvent') &&
                  e.params.args.originalEvent.hasOwnProperty('target'))
                  var newWidth = $(e.params.args.originalEvent.target).width();
                  var id = $(e.params.args.originalEvent.target).attr('id');
                  var container = $("span[aria-labelledby=""+id.split("-result")[0]+"-container"+""]");
                  $(container).parents('span.select2').width(newWidth + 21);

                  );


                  This is probably not fool-proof and is tied to the current API. But it gets the width of the element in the dropdown before the dropdown closes and then applies that to the container.



                  One thing of note, you may need to float the dropdown items to get their real size.



                  .select2-results__option 
                  float: left;
                  clear: both;






                  share|improve this answer













                  Just had to do something like this for a site



                  $(e).on("select2:closing", function(e) 
                  if (e.hasOwnProperty('params') &&
                  e.params.hasOwnProperty('args') &&
                  e.params.args.hasOwnProperty('originalEvent') &&
                  e.params.args.originalEvent.hasOwnProperty('target'))
                  var newWidth = $(e.params.args.originalEvent.target).width();
                  var id = $(e.params.args.originalEvent.target).attr('id');
                  var container = $("span[aria-labelledby=""+id.split("-result")[0]+"-container"+""]");
                  $(container).parents('span.select2').width(newWidth + 21);

                  );


                  This is probably not fool-proof and is tied to the current API. But it gets the width of the element in the dropdown before the dropdown closes and then applies that to the container.



                  One thing of note, you may need to float the dropdown items to get their real size.



                  .select2-results__option 
                  float: left;
                  clear: both;







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Oct 11 '17 at 17:08









                  rob-gordonrob-gordon

                  3831 gold badge8 silver badges29 bronze badges




                  3831 gold badge8 silver badges29 bronze badges





















                      0














                      $('.select2-search__field').attr('style','width:auto');

                      $('.select2-search__field[placeholder=""]').attr('style','width:10px');





                      share|improve this answer



























                        0














                        $('.select2-search__field').attr('style','width:auto');

                        $('.select2-search__field[placeholder=""]').attr('style','width:10px');





                        share|improve this answer

























                          0












                          0








                          0







                          $('.select2-search__field').attr('style','width:auto');

                          $('.select2-search__field[placeholder=""]').attr('style','width:10px');





                          share|improve this answer













                          $('.select2-search__field').attr('style','width:auto');

                          $('.select2-search__field[placeholder=""]').attr('style','width:10px');






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 26 at 7:30









                          AndreyAndrey

                          1




                          1



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37943730%2fhow-can-i-dynamically-resize-a-select2-input-to-be-the-same-width-as-the-selecte%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript