Response title
This is preview!
<script type='text/javascript'>
$(function() {
/*
This function will:
1. Create a data store for the select called ResizeToWidth.
2. Populate it with the width of the longest option, as approximated by span width.
The data store can then be used
*/
// Make a temporary span to hold the text of the options.
$('body').append("<span id='CurrentOptWidth'></span>");
$("#TheSelect option").each(function(i){
// If this is the first time through, zero out ResizeToWidth (or it will end up NaN).
if ( isNaN( $(this).parent().data('ResizeToWidth') ) ) {
$(this).parent().data( 'OriginalWidth', $(this).parent().width() );
$(this).parent().data('ResizeToWidth', 0);
$('CurrentOptWidth').css('font-family', $(this).css('font-family') );
$('CurrentOptWidth').css('font-size', $(this).css('font-size') );
$('CurrentOptWidth').css('font-weight', $(this).css('font-weight') );
}
// Put the text of the current option into the span.
$('#CurrentOptWidth').text( $(this).text() );
// Set ResizeToWidth to the longer of a) the current opt width, or b) itself.
//So it will hold the width of the longest option when we are done
ResizeToWidth = Math.max( $('#CurrentOptWidth').width() , $(this).parent().data('ResizeToWidth') );
// Update parent ResizeToWidth data.
$(this).parent().data('ResizeToWidth', ResizeToWidth)
});
// Remove the temporary span.
$('#CurrentOptWidth').remove();
$('#TheSelect').focus(function(){
$(this).width( $(this).data('ResizeToWidth') );
});
$('#TheSelect').blur(function(){
$(this).width( $(this).data('OriginalWidth') );
});
alert( $('#TheSelect').data('OriginalWidth') );
alert( $('#TheSelect').data('ResizeToWidth') );
});
</script>
<select id='TheSelect' style='width:50px;'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
<option value='42,693,748,756'>Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... </option>
<option value='5'>Five</option>
<option value='6'>Six</option>
<option value='7'>Seven...</option>
</select>
$('select').each(
function(i, select){
// Get the options for the select here... can I use select.each...?
}
);
© 2013 jQuery Foundation
Sponsored by and others.