-2

I have a select element with more options. The select has the width of the longest option text size. How can I set the select to have the width of the selected option? And when I click the select it should have the same width (of the selected option), but the rest of the options should have the width of the longest option text size.

Anticipated thanks!

EDIT

I've posted a wrong question. Actually I was looking for the easyest method of doing this. CSS / JS / jQuery.

Pascut
  • 3,291
  • 6
  • 36
  • 64

1 Answers1

3

simply I got the selected text and wrap it in a span to get its length , and then resize the select

try this example :

     <select id="sel">
         <option value="aaaa">aaaa</option>
         <option value="aaaaaaaa">aaaaaaaa</option>
         <option value="aaaaaaaaaaaa">aaaaaaaaaaaa</option>
         <option value="aaaaaaaaaaaaaaaa">aaaaaaaaaaaaaaaa</option>
         <option value="aaaaaaaaaaaaaaaaaaaa">aaaaaaaaaaaaaaaaaaaa</option>
     </select>

     <span id="hidnSpan">

     <span>

<script>

$(document).ready(function()
{
    $('#sel').change(function()
    {
        $('#sel').width( $('#hidnSpan').html($('#sel').find(":selected").text()).width())
    });
});


</script>
Mahmoud Farahat
  • 5,364
  • 4
  • 43
  • 59
  • Now it works, but on some pages I receive this error: TypeError: $(...) is null , at the line: $('#sel').width( $('#hidnSpan').html($('#sel').find(":selected").text()).width()) – Pascut Apr 22 '13 at 07:55
  • @Pascut make sure you have included `jQuery` reference in all pages or in master page – Mahmoud Farahat Apr 22 '13 at 08:39
  • 1
    I have a Magento website. The problem was that Magento is based on prototype.js and if I use jQuery there will be lots of conflicts. So I've translated this code into prototype.js code. Now it works good. Thanks for helping! – Pascut Apr 24 '13 at 06:10