Search code examples
jquerybootstrap-selectbootstrap-selectpicker

How to dynamically hide data-subtext for specific options for select-picker?


Select-picker

<select class="selectpicker form-control " name="name_id" >
            <option disabled selected value> -- select a category -- </option>
            <option id="classes" value="class" >class </option>
            <option id="schedule" value="schedule" >schedule</option>
        </select>

Javascript

document.querySelector('#classes').setAttribute("data-subtext", "Class 2");
$(".selectpicker").selectpicker('render').selectpicker("refresh");

Hide subtext

$('.selectpicker').selectpicker({
        showSubtext: false
 });

I try to unset the data-subtext by hiding it but nothing happens.

This is my reference: Trying to set data-live-search to select-picker

UPDATE :

Thank you @HMZ for the solution!.


Solution

  • As a proof of concept, i am using buttons to trigger changing the data-subtext of option elements but this can easily be triggered via some event or a different mechanism.

    var subTexts = {
      classes: "class class",
      schedule: "schedule"
    };
    
    $(function() {
    
      $('.selectpicker').selectpicker();
    
      $(".trigger").click(function() {
        SetSubText($(this).attr("data-option"), subTexts[$(this).attr("data-option")]);
      })
    });
    
    function SetSubText(option, subText) {
    
      //$(`#${option}`).attr("data-subtext", subText);
      document.querySelector(`#${option}`).setAttribute("data-subtext", subText)
      //$(`option:not("#${option}")`).attr("data-subtext", "");
      document.querySelectorAll(`option:not(#${option})`).forEach((function(x) {
        x.setAttribute("data-subtext", "");
      }));
    
      $(".selectpicker").selectpicker('render').selectpicker("refresh");
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css" rel="stylesheet"/>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>
    
    <select class="selectpicker form-control " name="name_id">
      <option disabled selected> -- Select a category -- </option>
      <option id="classes" value="class" data-subtext="Class Class">Class</option>
      <option id="schedule" value="schedule" data-subtext="schedule schedule">Schedule</option>
    </select>
    <button style="margin-top:3em" data-option="classes" class="btn btn-primary trigger" type="button">Trigger for classes</button>
    <button style="margin-top:3em" data-option="schedule" class="btn btn-primary trigger" type="button">Trigger for schedule</button>