Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 313
Matt Sims Avatar asked Jun 21 '16 11:06

Matt Sims


People also ask

How do I create a Select2 dynamically?

HTML. Create a <select class="select2_el" > element to initialize select2 on page load and create <div id="elements" > container to store <select > element on button click using jQuery AJAX.

How do I assign a value to Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data.text, data.id, false, false); $('#mySelect2').append(newOption).trigger('change');

What does Select2 () do?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.


2 Answers

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)

like image 147
NMC Avatar answered Sep 19 '22 07:09

NMC


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);
        
    });
});
like image 20
Michael Avatar answered Sep 19 '22 07:09

Michael