-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.simpleCombobox.js
executable file
·117 lines (99 loc) · 2.63 KB
/
jquery.simpleCombobox.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
$.Combobox = function(elem,options,param){
var c = {
length: 7
}
$.extend(c,param)
if($('#selectForCombobox').size()){
var select = $('#selectForCombobox');
}else{
var select = $('<select id="selectForCombobox" />').attr('size',(options.length>c.length)?c.length:options.length)
}
var makeList = function(options){
$.each(options,function(){
select.append('<option value="' + this + '">' + this + '</option>')
})
select
.bind('blur.combobox',hideList)
.bind('click.combobox',setValue)
.bind('keydown.combobox',function(e){
if(e.keyCode == '13'){ // Enter
setValue()
}
if(e.keyCode == 38 && $('option:first-child',this).attr('selected')){ // Up
hideList()
focusBack();
}
})
.mouseover(function(){
elem.unbind('blur.combobox')
})
.mouseout(function(){
elem.bind('blur.combobox',hideList)
})
return select;
}
var showList = function(){
var width = elem.width() + parseInt(elem.css('padding-left')) + parseInt(elem.css('padding-right')) + parseInt(elem.css('border-right-width')) + parseInt(elem.css('border-left-width'));
var specimen = $('body').find('>:first-child');
var offset = elem.offset();
offset.top = offset.top + elem.height() + parseInt(elem.css('padding-top')) + parseInt(elem.css('padding-bottom')) + parseInt(elem.css('border-top-width')) + parseInt(elem.css('border-bottom-width'));
select
.empty()
.css("width", "auto")
.css("visibility", "visible");
var list = makeList(options);
list
.css({
position: 'absolute',
top: offset.top,
left: offset.left,
width: width
})
.val(elem.val())
.appendTo('body')
.bind('blur.combobox',hideList)
if(width < select.width()){
width = select.width();
}
}
var hideList = function(){
select.remove()
elem
.bind('blur.combobox',hideList)
}
var focusBack = function(){
elem
.unbind('focus.combobox')
.focus()
.bind('focus.combobox',showList)
}
var setValue = function(){
hideList();
focusBack();
if(elem.val() != select.val()){
elem
.val(select.val())
.trigger("change")
}
}
var setEvent= function(){
elem
.bind('focus.combobox click.combobox',showList)
.bind('blur.combobox',hideList)
.bind('keydown.combobox',function(e){
if(e.keyCode == 40){ // Down
showList()
select.focus()
}
if(e.keyCode == 27){ // Esc
hideList()
}
})
}
setEvent();
}
$.fn.combobox = function(options){
return this.each(function(){
new $.Combobox($(this),options);
});
};