简体   繁体   中英

Deselect any option from Bootstrap-Select dropdown component

I have a Bootstrap-Select dropdown which is being populated from another source upon entering a certain string into a text input. Everything works up to the point where the first option is being selected by default and I want to prevent this so the user has to select an option.

Please see a demo here: https://jsfiddle.net/moxxah8r/

Code is as follows:

<style>
  .form-control,
  .selectpicker {
    width: 220px;
  }

  #postalcode {
    text-transform: uppercase;
    margin-right: 10px;
  }
</style>

<div style="padding: 10px;">
  <div style="display: flex;">
    <input name="postalcode" id="postalcode" type="text" class="form-control" autocomplete="postal-code">
    <select name="address" id="address" class="selectpicker" disabled>
      <option value="0" selected>&nbsp;</option>
    </select>
  </div>
</div>

<script>
  var data = ["1 Street Name", "2 Street Name", "3 Street Name", "4 Street Name", "5 Street Name"];
  $('#postalcode').on('input', function(e) {
    var pattern = new RegExp('^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$');
    var text = $('#postalcode').val().toUpperCase();

    if (pattern.test(text)) {
      $('#address').empty();
      $.each(data, function(i, value) {
        $('#address').append($('<option>').text(value).attr('value', value));
      });
      $('#address option').prop('selected', false);
      $('#address').prop('disabled', false);
      $('#address').selectpicker('refresh');
    } else {
      $('#address').empty().append('<option value="0" selected>&nbsp;</option>');
      $('#address').prop('disabled', true);
      $('#address').selectpicker('refresh');
    }
  });
</script>

The first thing you need to do is remove selected from your pre-defined <option> as that creates the problem by design, rather than by default.

Instead of relying on a blank <option> hack, why not make use of some of the built-in features of Bootstrap Select? By specifying a title in the <select> element you can create a pseudo-placeholder. This prevents the first item in the dropdown menu from being selected by default:

<select name="address" id="address" class="selectpicker" title="Make Your Selection" disabled>...</select>

You can read about this feature as well as several other labeling options at Bootstrap Select's documentation for Custom Button Text

https://silviomoreto.github.io/bootstrap-select/examples/#placeholder

You can do this with jQuery. Remove any blank option tag and call this on your event:

$('select#address').val([]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM