In this article I will explain with an example, how to adjust width of HTML SELECT (DropDown) dynamically using jQuery.
HTML Markup
The following HTML Markup consists of an HTML SELECT (DropDown) element with some options.
<select id="Select1" style="width: 75px;">
<option value="1">Mumbai</option>
<option value="2">Delhi</option>
<option value="3">Chandigarh City</option>
</select>
Adjusting width of HTML SELECT (DropDown) using jQuery
Inside the jQuery document ready event handler, the HTML SELECT (DropDown) has been assigned with a mouseover event handler.
Inside this event handler, the AdjustWidth JavaScript function is called.
Inside the AdjustWidth JavaScript function, a loop will be executed over the items of HTML SELECT (DropDown) element and the maximum Text length is determined.
Finally, the width is set to the HTML SELECT (DropDown) element.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type = "text/javascript">
$(function () {
$("select").mouseover(function () {
AdjustWidth(this);
});
});
function AdjustWidth(ddl) {
var maxWidth = 0;
$(ddl).find('option').each(function (i) {
if ($(this).text().length > maxWidth) {
maxWidth = $(this).text().length;
}
});
$(ddl).css("width", maxWidth * 7 + "px");
}
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads