bodley
bodley

Reputation: 187

Define max visible length of select/option element

I'd like to create a <select> field. By default the length of this field is defined by the longest <option>. Is it possible to define the maxlength of visible select options when I need to have whole select field 100% of parent div?

Let me show you this in code:

<div class = "my-container">
  <select name="myselect" id="myselect">
    <option>abc</option>
    <option>xyz1</option>
    <option>really really long long long long long string</option>
  </select>
</div>

styles:

.my-container{
  width:200px;
}
#myselect{
  width: 100%;
}

Now I want to have my select field 100% width but! I want to display in this select let's say only 20 words (or some px value) of option value and then "..." example:

Verylong
Verylonglonglong... (original value: Verylonglonglong1234567789)

I tried to add overflow property to #myselect, but it does not work for me.

Upvotes: 2

Views: 4864

Answers (1)

silviagreen
silviagreen

Reputation: 1729

A JQuery solution to your problem:

var maxLength = 15;
$('#myselect > option').text(function(i, text) {
    if (text.length > maxLength) {
        return text.substr(0, maxLength) + '...';  
    }
});
.my-container{
  width:200px;
}
#myselect{
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class = "my-container">
  <select name="myselect" id="myselect">
    <option>abc</option>
    <option>xyz1</option>
    <option>really really long long long long long string</option>
  </select>
</div>

Upvotes: 2

Related Questions