-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathselect-togglebutton.js
More file actions
83 lines (69 loc) · 3.15 KB
/
select-togglebutton.js
File metadata and controls
83 lines (69 loc) · 3.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
(function($) {
// Define the togglebutton plugin.
$.fn.togglebutton = function(opts) {
// Apply the users options if exists.
var settings = $.extend( {}, $.fn.togglebutton.defaults, opts);
// For each select element.
this.each(function() {
var self = $(this);
var multiple = this.multiple;
// Retrieve all options.
var options = self.children('option');
// Create an array of buttons with the value of select options.
var buttons = options.map(function(index, opt) {
var button = $("<button type='button' class='btn btn-default'></button>")
.prop('value', opt.value)
.text(opt.text);
// Add an `active` class if the option has been selected.
if (opt.selected)
button.addClass("active");
// Return the button.
return button[0];
});
// For each button, implement the click button removing and adding
// `active` class to simulate the toggle effect. And also change the
// select selected option.
buttons.each(function(index, btn) {
$(btn).click(function() {
// Retrieve all buttons siblings of the clicked one with an
// `active` class !
var activeBtn = $(btn).siblings(".active");
var total = [];
// Remove all selected property on options.
self.children("option:selected").prop("selected", false);
// Check if the clicked button has the class `active`.
// Add or remove it according to the check.
if ($(btn).hasClass("active")) {
$(btn).removeClass("active");
}
else {
$(btn).addClass("active");
options.val(btn.value).prop("selected", true);
total.push(btn.value);
}
// If the select allow multiple values, remove all active
// class to the other buttons (to keep only the last clicked
// button).
if (!multiple) {
activeBtn.removeClass("active");
}
// Push all active buttons value in an array.
activeBtn.each(function(index, btn) {
total.push(btn.value);
});
// Change selected options of the select.
self.val(total).change();
});
});
// Group all the buttons in a `div` element.
var btnGroup = $("<div class='btn-group'>").append(buttons);
// Include the buttons group after the select element.
self.after(btnGroup);
// Hide the display element.
self.hide();
});
};
// Set the defaults options of the plugin.
$.fn.togglebutton.defaults = {
};
}(jQuery));