Site icon Puneet Sharma – Freelance Web Developer

Make select tag width equal to the selected option

The following script resizes the width of HTML's tag dynamically according to the width of the selected option.

The following script resizes the width of HTML’s tag dynamically according to the width of the selected option. This may be used in places where you want to customize the select tag and make it look like a dropdown select.

Demo

Open demo in a full window – https://demos.webdevpuneet.com/misc/dynamic-select-width/index.html

Source code


<!DOCTYPE html>
<html>
<head>
  <title>Dynamic select width</title>
  <meta name="description" content="Resizes width of HTML select tag according to the selected option" />
  <style>
    .resizeselect{
      border:1px solid #000000;
    }
  </style>
</head>
<body>
  <h1>Dynamic Width of HTML Select Tag</h1>
  <p>Resize the width of HTML's <select> tag according to the width of the selected option.</p>

  <div class="demo">
    <select id="resizing_select" class="resizeselect">
      <option selected>Address one</option>
      <option>Address two - this is a medium text</option>
      <option>This is a Long Address for testing purpose</option>
      <option>This one is a long text - this one is a long text - this one is a long text</option>
    </select>
    <select style="display:none;visibility:hidden;" id="width_tmp_select"><option id="width_tmp_option"></option></select><!-- For select size -->
  </div>


  <!-- Scripts -->
  <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  <script>
    /* Resize select width according to selected text */
    $(document).ready(function() {
      $("#width_tmp_option").html($('#resizing_select option:selected').text());
      $('#resizing_select').width($("#width_tmp_select").width());

      $('#resizing_select').change(function(){
        $("#width_tmp_option").html($('#resizing_select option:selected').text());
        $(this).width($("#width_tmp_select").width());
      });
    });
  </script>
</body>
</html>

Related Queries:

Exit mobile version