Skip to content

Clear selected value programmatically #240

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
sliekens opened this issue Jan 31, 2017 · 1 comment
Open

Clear selected value programmatically #240

sliekens opened this issue Jan 31, 2017 · 1 comment
Labels
enhancement A feature request

Comments

@sliekens
Copy link

sliekens commented Jan 31, 2017

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 to the empty string and then refresh the combobox. This is useful if 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
Copy link

maksimu commented Feb 2, 2017

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

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

@tiesont tiesont added the enhancement A feature request label Jan 31, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement A feature request
Projects
None yet
Development

No branches or pull requests

3 participants