Dynamically truncate <option> text to fit <select> list

为君一笑 提交于 2019-12-04 22:38:55

Using css and jQuery :

select, option.selected {
    width:100px;
    overflow:hidden;
    white-space:nowrap;
    text-overflow:ellipsis;
}

jQuery

$('select').on('change',function(){
    $(this).find('option').removeClass('selected');
    $(this).find('option:selected').addClass('selected');
});

demo

I believe what you're looking for is:

option {
  width: 200px; // Adjustable
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

That will automatically force the select options to be the specified width, and convert any 'overflowing' text to ellipsis that remains within the bounds :)

Hope this helps!

Lăng Bùi

I found the solution for chrome here:

https://stackoverflow.com/a/26627224/4743939

Using this approach, the caret icon in select tag will disappear, so you might want to use a background image for it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!