danielfarrell / bootstrap-combobox

A combobox plugin that works with twitter bootstrap
849 stars 328 forks source link

Clear selected value programmatically #240

Open sliekens opened 7 years ago

sliekens commented 7 years ago

Since there is no way to programmatically clear the selected value of a bootstrap-combobox, and because the author is unresponsive to feedback and PRs (#146, #158, #168, #235), I came up with a piece of code that lets you clear the selected value.

Include the following code in your page, before your own code but after the bootstrap-combobox.js file.

(function (methods) {
  methods.clear = function () {
    if (!this.selected) {
      return;
    }

    this.$element.val('').trigger('change');
    this.$target.val('').trigger('change');
    this.$source.val('').trigger('change');
    this.$container.removeClass('combobox-selected');
    this.selected = false;
  };

  (function (refresh) {
    methods.refresh = function () {
      refresh.apply(this);
      if (this.selected && this.$source.val() === '') {
        this.$element.val('').trigger('change');
        this.$target.val('').trigger('change');
        this.$container.removeClass('combobox-selected');
        this.selected = false;
      }
    };
  })(methods.refresh);
})($.fn.combobox.Constructor.prototype);

With this code you can explicitly clear the selected value.

$('.combobox').data('combobox').clear();

Or you can instead set the value of the underlying element is controlled by code that you can't modify.

$('.combobox').data('combobox').$source.val('');
$('.combobox').data('combobox').refresh();

Demo https://jsfiddle.net/sliekens/gdnm9hut/

maksimu commented 7 years ago

Maybe it is a good time to fork it and maintain it somewhere else?

Anyway, thank for the code sample, just what I needed!