Search code examples
javascripthtmldrop-down-menubootstrap-4bootstrap-selectpicker

How can I set fixed width for options(dropdown) in bootstrap selectpicker


This is code

  <select class="selectpicker form-control" data-live-search="true" id="subject_teacher_drop_down">
       <option>English</option>
       <option>Methodology of social science with special reference to economics</option>
  </select>

I want to make the width of the dropdown say for example 100 px . Now width is equal to the size of the biggest option.


Solution

  • Guyz, I came up with a simple answer. We can use the 'datacontent' attribute in the select option to display the values of select options thereby changing its width :) The code is:

     <select class="selectpicker form-control" data-live-search="true" id="subject_teacher_drop_down">
       <option data-content="English">English</option>
       <option data-content="Methodology of social...">Methodology of social science with special reference to economics</option>
    </select>
    

    If you are passing the values dynamically, do like this :

      <select class="selectpicker form-control" data-live-search="true">
              <?php foreach ($subjectList as $subjects) : ?>
                 <option data-content=" <?php $a =$subjects->getName();$b = substr($a, 0, 35);$y = $b . "...";if($a > $b)echo $y; else echo $a;?>" id="<?php echo $subjects->getId(); ?>" name="<?php echo $subjects->getName(); ?>" value="<?php echo $subjects->getName(); ?>">
                    <?php echo $subjects->getName(); ?>
                </option>
           <?php endforeach; ?>
      </select>