Faisal Malik
Faisal Malik

Reputation: 45

How to increase/decrease 'select' option width after the user wants to select an option

I have a select box where I hardcode with width. I want the width according to selected text. If text is long then width automatically expand and if text is short then it will be adjust according to it. This is my code.

.post-select {
     border:none;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    }
<select id="discoverselect" class="post-select">
        
        <option>All Sports</option>
        <option>OCR</option>
        <option>Triathlon</option>
        <option>Running and Marathon</option>
        <option>Ultramarathon</option>
        <option>Cycling</option>

</select>

Upvotes: 2

Views: 132

Answers (2)

Adeel Gill
Adeel Gill

Reputation: 353

if you can find the length you can change the width according to your characters.

To find the length

function textWidth(str){
    var span = $("<span>"+str+"</span>");
    $("body").append(span);
    var width = span.width();
    span.remove();
    return width;
    };

$(document).ready(function(){
	$("#discoverselect").change(function(){
    $(this).width(textWidth($(this).find("option:selected").text()));
    }).trigger("change");
    });
function textWidth(str){
	var span = $("<span>"+str+"</span>");
    $("body").append(span);
    var width = span.width();
    span.remove();
    return width;
    };
.post-select {
     border:none;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="discoverselect" class="post-select">        
        <option>All Sports</option>
        <option>OCR</option>
        <option>Triathlon</option>
        <option>Running and Marathon</option>
        <option>Ultramarathon</option>
        <option>Cycling</option>
</select>

Upvotes: 1

Diptox
Diptox

Reputation: 1809

Demo

$(document).ready(function()
{
    $("#discoverselect").change(function()
    {
        $(this).width(textWidth($(this).find("option:selected").text())+20);
    }).trigger("change");
});

function textWidth(str)
{
    var span = $("<span style='white-space: nowrap;'>"+str+"</span>");
    $("body").append(span);
    var width = span.width();
    span.remove();
    return width;
};

Upvotes: 0

Related Questions