-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathselectField.js
91 lines (70 loc) · 2.06 KB
/
selectField.js
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
84
85
86
87
88
89
90
91
/**
* Initialize a custom select field
*/
$.fn.selectField = function() {
'use strict';
return this.each(function() {
var $this = $(this);
var options = '';
// Has selectField already been run on this element?
if ($this.attr('data-assigned')) return;
// Make sure it doesn't get run again
$this.attr('data-assigned', '1');
// Set the value
var $selected = $this.find('.selected');
if (!$selected.length) {
$selected = $this.children().first();
}
$this.attr('data-value', $selected.attr('data-value'));
$this.prepend('<div class="right"><i class="fa fa-chevron-down"></i></div>');
var $icon = $($this.find('.right i'));
// Create a dropdown element
var $dropdown = $('<div class="select-dropdown hidden"></div>');
$dropdown.css('width', ($this.width() + 2) + 'px');
// Prepare the dropdown
$this.children().each(function() {
var $this = $(this);
if (!$this.hasClass('option')) return;
options += '<a href="javascript:void(0)" data-value="' + $this.attr('data-value') + '">' + $this.html() + '</a>';
});
// Set the dropdown content
$dropdown.html(options);
$this.after($dropdown);
var show = function() {
$dropdown.removeClass('hidden');
$icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
};
var hide = function() {
$dropdown.addClass('hidden');
$icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
};
/**
* Handle open/close of select field
* @param Object e
*/
$this.on('click', function(e) {
if ($dropdown.hasClass('hidden')) {
show();
} else {
hide();
}
e.stopPropagation();
$('body').off('click');
$('body').on('click', hide);
});
/**
* Handle option selection
* @param Object e
*/
$dropdown.on('click', function(e) {
hide();
var value = $(e.target).attr('data-value');
// UI changes
$this.find('.selected').removeClass('selected');
$this.find('[data-value="' + value + '"]').addClass('selected');
$this.attr('data-value', value);
$this.trigger('change', value);
e.stopPropagation();
});
});
};