7

I want to put a dropdown list on my page, As one option is too long, when I click the select menu, it will expand and cover the other part of the page.

<select id="selectlist" name="SelectProgram">

    <option value="LIR" >LIR</option>
        <option value="How to word wrap text in HTML?">How to word wrap text in HTML? CSS / HTML text wrap for webkit</option>

The second option is too long and will expand. Is there any way I could wrap such a long text into 2 lines? Thank you!

Chengzhi
  • 2,531
  • 2
  • 27
  • 41
  • 3
    No, you can't wrap the text in a native select. I suggest setting the width of the select to a fixed width. – Kevin B Aug 06 '12 at 19:01

3 Answers3

6

Seeing as the value and text of a Select can be very different. I would say if in the event a string thats in your select for the text is longer than X truncate it.

Example with jquery

$('#myselect option').each(function()
{
    var myStr = $(this).text();
    if(myStr.length > 15){$(this).text(myStr.substring(15));}
});

put that in your document ready, and it will trim your text down to a better size, wrapping your elements in a div that will hide the overflow is going to make something of a mess later, and you will be back here trying to solve a similar issue caused by that for strings that are smaller.

chris
  • 36,115
  • 52
  • 143
  • 252
  • +1, I wouldn't have thought of this – bkconrad Aug 06 '12 at 19:14
  • 1
    Two things to improve this code: use `substring(0,15)` or else the FINAL 15 characters will be grabbed. In addition, I like to add ellipses whenever option text is truncated, so the user knows it has been, such as: `text(myStr.substring(0,15) + '...')`. Answer edited to include these... – Marcus Mar 31 '14 at 16:58
  • Another quick comment: be careful about extra whitespace in your HTML between option texts when using this Javascript. Your browser might have scrubbed it out, but the JS `length` method will not. – Marcus Mar 31 '14 at 17:00
  • This chopped off the first few strings. My users won't know what they are selecting. I'd prefer a text wrap not a text chop off. – Ezeilo Uchenna Jul 21 '19 at 15:52
5

Setting a fixed width can be done without the wrapping div by simply using

<select id="selectlist" name="SelectProgram" style="width: 500px">
   <option value="LIR" >LIR</option>
   <option value="How to word wrap text in HTML?">How to word wrap text in HTML? CSS / HTML text wrap for webkit</option>
</select>

In practice, you should put width: 500px in a matching rule in your CSS file.

bkconrad
  • 2,620
  • 3
  • 20
  • 30
0

wrap that input in a div, put some width for div, so that line will not go outside the div, lik below :

<div id="something" style="width:500px">
  <select id="selectlist" name="SelectProgram">
     <option value="LIR" >LIR</option>
     <option value="How to word wrap text in HTML?">How to word wrap text in HTML? CSS / HTML text wrap for webkit</option>
  </select>
</div>
Shreedhar
  • 5,502
  • 3
  • 22
  • 27