-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.form-conditionals.js
More file actions
102 lines (89 loc) · 2.69 KB
/
jquery.form-conditionals.js
File metadata and controls
102 lines (89 loc) · 2.69 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* jQuery Conditionals 1.0.0
*
* Copyright 2015 n7 Studios
* Released under the MIT license.
* http://jquery.org/license
*/
(function( $ ) {
"use strict";
/**
* Create .conditional() function
*
* @param object options Override Default Settings
*/
$.fn.conditional = function(options) {
// Default Settings
var settings = $.extend({
data: 'conditional',
value: 'conditional-value',
displayOnEnabled: 'conditional-display'
}, options);
// Setup conditionals on each DOM element
this.each(function() {
// Check for conditional elements
if ( typeof $( this ).data( settings.data ) === 'undefined' ) {
return true;
}
// Setup vars
var conditionalElements,
displayOnEnabled,
value,
displayElements;
// Toggle + toggle on change
$( this ).on( 'change', function() {
// List the DOM elements to toggle
conditionalElements = $( this ).data( settings.data ).split(',');
// Determine whether to display DOM elements when the input is 'enabled'
displayOnEnabled = $( this ).data( settings.displayOnEnabled );
if ( typeof displayOnEnabled === 'undefined' ) {
displayOnEnabled = true;
}
// Determine the value required to display elements
value = $( this ).data( settings.value );
if ( typeof value === 'undefined' ) {
value = '';
}
// By default, don't display elements
displayElements = false;
// Determine whether to display relational elements or not
switch ( $( this ).attr( 'type' ) ) {
case 'checkbox':
if ( displayOnEnabled ) {
displayElements = $( this ).is( ':checked' );
} else {
displayElements = ( $( this ).is( ':checked' ) ? false : true );
}
break;
default:
if ( displayOnEnabled ) {
if ( value !== '' ) {
displayElements = ( ( String( $( this ).val() ) !== String( value ) ) ? false : true );
} else {
displayElements = ( ( $( this ).val() === '' || $( this ).val() === '0' ) ? false : true );
}
} else {
if ( value !== '' ) {
displayElements = ( ( $( this ).val() !== value ) ? true : false );
} else {
displayElements = ( ( $( this ).val() === '' || $( this ).val() === '0' ) ? true : false );
}
}
break;
}
// Show/hide elements
for (var i = 0; i < conditionalElements.length; i++) {
if ( displayElements ) {
$( '#' + conditionalElements[i] ).fadeIn( 300 );
} else {
$( '#' + conditionalElements[i] ).fadeOut( 300 );
}
}
});
// Trigger a change on init so we run the above routine
$ ( this).trigger( 'change' );
});
// Return DOM elements
return this;
};
})(jQuery);