1

Setting the width of select2 using css is overridden by the javascript call of the select2

// javascript
$(function() {
  renderSelect("select");
});

# HAML example (Rails)
 = select_tag "countries", options_for_select(@countries), class: 'some-ignored-css-class'

related: How to control the width of select tag?

Community
  • 1
  • 1
xxjjnn
  • 14,591
  • 19
  • 61
  • 94

2 Answers2

1

The problem isn't javascript, the issue is that you're not preserving the CSS.

The only way to set the width is to use CSS. Even your JS sets the CSS (.width):

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). They both set the CSS "style" element

A better way is to either set the CSS on a "container" element, or make sure you're persisting the CSS whenever you call the renderSelect function:


Container

#app/assets/stylesheets/application.css
.container select { width: 50px; }

#app/views...
.container= select_tag "countries", options_for_select(@countries)

Using a container will allow you to set the CSS on the container, removing the need for the class on the select itself. Whilst it means adding a container div, it will give you the most autonomy.

--

JS

The alternative will be to change the renderSelect function to take the class of the current select & append it to the new element.

Since I don't know your renderSelect function, I can only provide that level of suggestion.

Richard Peck
  • 76,116
  • 9
  • 93
  • 147
-1

A solution is to javascript again

// javascript
$(function() {
  renderSelect("select");
  $("div#s2id_countries").width(300);
});

# HAML example (Rails)
 = select_tag "countries", options_for_select(@countries), class: 'some-ignored-css-class'

ahh, Javascript, the cause of, and solution to, all of life's problems

(any improvements?)

xxjjnn
  • 14,591
  • 19
  • 61
  • 94