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


i have select box hardcode width. want width according selected text. if text long width automatically expand , if text short adjust according it. 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 , marathon</option>          <option>ultramarathon</option>          <option>cycling</option>    </select>

if can find length can change width according characters.

to find 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 , marathon</option>          <option>ultramarathon</option>          <option>cycling</option>  </select>


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -