bootstrap switch get custom value instead of true false

1.3k views Asked by At

I am trying to use bootstrap switch with below code in html,

<input type="checkbox" id="queue_status" checked class="make-switch" data-size="small" data-off-text="Disable" data-on-text="Enable" checked data-on-color="success" data-off-color="warning">

But this returns either 'true' or 'false' as value,

How can we get custom value as selection? Like Enable or Disable with switch selection as above?

1

There are 1 answers

0
Slava Utesinov On

You can tune bootstrap-switch plugin(I used v3.3.2) for your purposes by making little changes (attention - it may cause side effects):

FROM:

$.fn.bootstrapSwitch = function() {
  var args, option, ret;
  option = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
  ret = this;
  this.each(function() {
    var $this, data;
    $this = $(this);
    data = $this.data("bootstrap-switch");
    if (!data) {
      $this.data("bootstrap-switch", data = new BootstrapSwitch(this, option));
    }
    if (typeof option === "string") {
      return ret = data[option].apply(data, args);
    }
  });
  return ret;
};

TO:

$.fn.bootstrapSwitch = function() {
  var args, option, ret;
  option = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
  ret = this;
  this.each(function() {
    var $this, data;
    $this = $(this);
    data = $this.data("bootstrap-switch");
    if (!data) {
      $this.data("bootstrap-switch", data = new BootstrapSwitch(this, option));
    }
    if (typeof option === "string") {
        //this section was modified (start)!
        var temp = data[option].apply(data, args);            
        return ret = option == 'state' ? data[temp ? 'onText' : 'offText'].apply(data, args) : temp;
        //this section was modified (end)!
    }
  });
  return ret;
};

IMPLEMENTATION:

var res = $('#mycheckbox').bootstrapSwitch('state');
//res == 'Enable' or 'Disable'

P.S. if you will use it only once, you can simply do this (without doing any changes in plugin):

var element = $('#mycheckbox');
var res = element.bootstrapSwitch(element.bootstrapSwitch('state') ? 'onText' : 'offText');