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>