1

I'm using jQuery and trying to animate a <select> box where the width would be determined by the longest <option>. The select is populated with ajax depending on the users previous selections.

I can animate the <select> just fine, but I don't know how to determine the width of the longest <option>. Any ideas how I can do this so the <select> animates to the correct size?

I've tried doing it with static values to start but still can't figure how to determine the width I need to animate to.

<script type="text/javascript"> 
   $(document).ready(function(){
      $("button").click(function(){
         $("select").animate({width:"what goes here?","slow");
       });
    });
</script> 
<select id = "mySelect" style = "width: 0px;">
   <option value = "yes">Yes</option
   <option value = "no">no</option>
   <option value = "this is extra long text">this is extra long text</option>
</select>

--edit-- Here is the jQuery I ended with to account for ie7's suckage

<script type="text/javascript">
    $.ajaxSetup ({
        cache: false// Disable caching of AJAX responses
    });
    $("document").ready(function(){
        $("#btn").click(function(){
            w = $("#mySelect").width();     
            $.ajax({
                url: "../ajax/optionTest.cfm",
                context: document.body,
                success: function(data){
                    $("#mySelect").css("width",w);
                    $("#mySelect").html(data);
                    if( $("#mySelect option").width() > 0){
                        $("#mySelect").animate({width:$("#mySelect option").width()},"slow");
                    }else{
                        $("#mySelect").css("visibility","hidden");
                        $("#mySelect").css("width","auto");
                        newWidth = $("#mySelect").width();
                        $("#mySelect").css("width",w+4);
                        $("#mySelect").css("visibility","visible");
                        $("#mySelect").animate({width:newWidth},"slow");
                    };  
                }
            });
        });
    });
</script>
genericHCU
  • 4,394
  • 2
  • 22
  • 34
  • most browsers automatically do this for you, up to a certain limit. You could looping $("option").width() – paulcol. Dec 20 '11 at 12:51
  • You probably want to do some calculation based on the `.length` of the longest property (found by a loop), some trial and error in this case, I just can't do some proper testing right now. – Madara's Ghost Dec 20 '11 at 12:52
  • @crolpa - unfortunately the width of the `option` elements is zero initially – sje397 Dec 20 '11 at 13:03

3 Answers3

2
function sincdec() {
  if (($("select").attr("size")) == 1) {
    var mi = "inc";
    var s = 1;
    setInterval(function () {
      if (s < 10) {
        if ($('#select').is(':hover') === true) {
          s++;
          $("select").attr("size", s);
          $("span").html(s);
        }
      }
    }, 10);
  } else if (($("select").attr("size")) == 10) {
    var mi = "dec";
    var s = 10;
    setInterval(function () {
      if (s > 1) {
        if ($('#select').is(':hover') === false) {
          s--;
          $("select").attr("size", s);
          $("span").html(s);
        }
      }
    }, 10);
  }
};

$("select").hover(function (e) {
  sincdec();
});

jsfiddle sample here

Matt K
  • 7,207
  • 5
  • 39
  • 60
krabat1
  • 31
  • 3
  • Thanks, that's an interesting effect but not what I was after, 6 months ago. :) thanks for the necro post, though. – genericHCU Jul 05 '12 at 14:18
1

Your html

   <select id = "mySelect" style = "width: 0px;">
       <option value = "yes">Yes</option>
       <option value = "no">nooooooooooooo</option>
       <option value = "this is extra long text ">this is extra long text</option>
    </select>
    <button>test</button>

Javascript

$(document).ready(function() {
    $("button").click(function() {
        $("select").animate({
            width: $('select option').width()},
            "slow");
    });
});

By default all options take the width of the biggest option.

This code may not work with IE :@

I made a "dirty" modification

http://jsfiddle.net/YmJvT/20/

Bouchaala Sabri
  • 647
  • 4
  • 9
  • I might have spoken to soon. This doesn't seem to work in IE7 which is what I have to work with at the moment (at least until March 2012). $('select option').width() = 0 all the time. Not sure about IE8 – genericHCU Dec 20 '11 at 13:49
  • Came up with this as a workaround. Thanks again for the help! if($("#mySelect option").width() > 0){$("#mySelect").animate({width:$("#mySelect option").width()},"slow");}else{$("#mySelect").css("visibility","hidden");$("#mySelect").css("width","auto");newWidth = $("#mySelect").width();$("#mySelect").css("width",w);$("#mySelect").css("visibility","visible");$("#mySelect").animate({width:newWidth},"slow");}; – genericHCU Dec 20 '11 at 14:56
  • I modified the code, you may use the second solution for IE only. – Bouchaala Sabri Dec 20 '11 at 15:12
  • Thank you for the effort. As the text size on our site is customizable I don't think that solution would work anyway. I updated the OP with my final solution. – genericHCU Dec 20 '11 at 17:50
0

Here's a method that uses a fixed letter size (8 pixels):

$("button").click(function(){
    var max = 0;
    $("option").each(function() { 
        var l = $(this).text().length;
        if(l > max) max = l;
    });
    $("select").animate({width:max * 8}, "slow");
});

..but you can get more accurate calculations for the pixel width of a string. Check out this answer: Calculate text width with JavaScript

Community
  • 1
  • 1
sje397
  • 41,293
  • 8
  • 87
  • 103