Shorten select option text if stretches wider than select element's max-width.

Problem: Some select options' text can stretch wider than the select element. Solution: Check the text of each select option and shorten if text length is wider than allowed for the select element. Requirement: <select> element must have a 'max-width' in pixels set. Why? This code reads the max-width value to decide the character length to allow for option text. Added feature: Shows the entire text of the selected option in a tooltip when user moves mouse over collapsed select element.

HTML

<select class="shortenedSelect">
    <option value="0" disabled>Please select an item</option>
    <option value="1">Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more</option>
</select>

CSS

.shortenedSelect {
    max-width: 350px;
}

JavaScript

// Shorten select option text if it stretches beyond max-width of select element
$.each($('.shortenedSelect option'), function(key, optionElement) {
    var curText = $(optionElement).text();
    $(this).attr('title', curText);

    // Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system.
    var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10) / 7.3);
    
    if (curText.length > lengthToShortenTo) {
        $(this).text('... ' + curText.substring((curText.length - lengthToShortenTo), curText.length));
    }
});

// Show full name in tooltip after choosing an option
$('.shortenedSelect').change(function() {
    $(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title')));
});