forked from znbailey/jQuery-Dependent-Fields
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjquery.dependent.fields.js
52 lines (47 loc) · 1.74 KB
/
jquery.dependent.fields.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
(function($){
$.fn.dependsOn = function(element, value, enclosing_tag) {
// enclosing tag is span by default
if (!enclosing_tag) {
enclosing_tag = 'span';
}
var elements = this;
//add change handler to element
$(element).change(function(){
var $this = $(this);
var showEm = false;
if ( $this.is('input[type="checkbox"]') ) {
showEm = $this.is(':checked');
} else if ( $this.is('input[type="radio"]') ) {
showEm = $this.is(':checked');
} else if ( $this.is('select') ) {
// var fieldValue = $this.find('option:selected').val();
var fieldValue = $this.val();
if ( !value ) {
showEm = fieldValue && $.trim(fieldValue) != '';
} else if (typeof(value) === 'string') {
// check for value in multiple selection
if ($.isArray(fieldValue)) {
showEm = ($.inArray(value, fieldValue) !== -1);
} else {
showEm = value == fieldValue;
}
} else if ($.isArray(value)) {
// check for multiple values
if ($.isArray(fieldValue)) {
// in multiple selection
showEm = $.grep(fieldValue,function(el,i){return $.inArray(el,value) !== -1}).length > 0;
} else {
// in single selected item
showEm = ($.inArray(fieldValue, value) !== -1);
}
}
}
elements.closest(enclosing_tag).toggle(showEm);
});
//hide the dependent fields
return elements.each(function(){
var $this = $(this);
$this.closest(enclosing_tag).hide();
});
};
})( jQuery );