f739746f830c3f6d92f4424216fd7d13166fd627
2 * HTMLForm enhancements:
3 * Set up 'hide-if' behaviors for form fields that have them.
8 * Helper function for hide-if to find the nearby form field.
10 * Find the closest match for the given name, "closest" being the minimum
11 * level of parents to go to find a form field matching the given name or
12 * ending in array keys matching the given name (e.g. "baz" matches
18 * @param {string} name
19 * @return {jQuery|null}
21 function hideIfGetField( $el
, name
) {
23 suffix
= name
.replace( /^([^\[]+)/, '[$1]' );
25 function nameFilter() {
26 return this.name
=== name
||
27 ( this.name
=== ( 'wp' + name
) ) ||
28 this.name
.slice( -suffix
.length
) === suffix
;
31 for ( $p
= $el
.parent(); $p
.length
> 0; $p
= $p
.parent() ) {
32 $found
= $p
.find( '[name]' ).filter( nameFilter
);
33 if ( $found
.length
) {
41 * Helper function for hide-if to return a test function and list of
42 * dependent fields for a hide-if specification.
49 * @return {jQuery} return.0 Dependent fields
50 * @return {Function} return.1 Test function
52 function hideIfParse( $el
, spec
) {
53 var op
, i
, l
, v
, $field
, $fields
, fields
, func
, funcs
, getVal
;
64 for ( i
= 1; i
< l
; i
++ ) {
65 if ( !$.isArray( spec
[ i
] ) ) {
66 throw new Error( op
+ ' parameters must be arrays' );
68 v
= hideIfParse( $el
, spec
[ i
] );
69 fields
= fields
.concat( v
[ 0 ].toArray() );
72 $fields
= $( fields
);
79 for ( i
= 0; i
< l
; i
++ ) {
80 if ( !funcs
[ i
]() ) {
91 for ( i
= 0; i
< l
; i
++ ) {
103 for ( i
= 0; i
< l
; i
++ ) {
104 if ( !funcs
[ i
]() ) {
115 for ( i
= 0; i
< l
; i
++ ) {
116 if ( funcs
[ i
]() ) {
125 return [ $fields
, func
];
129 throw new Error( 'NOT takes exactly one parameter' );
131 if ( !$.isArray( spec
[ 1 ] ) ) {
132 throw new Error( 'NOT parameters must be arrays' );
134 v
= hideIfParse( $el
, spec
[ 1 ] );
137 return [ $fields
, function () {
144 throw new Error( op
+ ' takes exactly two parameters' );
146 $field
= hideIfGetField( $el
, spec
[ 1 ] );
148 return [ $(), function () {
154 if ( $field
.first().prop( 'type' ) === 'radio' ||
155 $field
.first().prop( 'type' ) === 'checkbox'
157 getVal = function () {
158 var $selected
= $field
.filter( ':checked' );
159 return $selected
.length
? $selected
.val() : '';
162 getVal = function () {
170 return getVal() === v
;
175 return getVal() !== v
;
180 return [ $field
, func
];
183 throw new Error( 'Unrecognized operation \'' + op
+ '\'' );
187 mw
.hook( 'htmlform.enhance' ).add( function ( $root
) {
188 $root
.find( '.mw-htmlform-hide-if' ).each( function () {
189 var v
, $fields
, test
, func
,
191 spec
= $el
.data( 'hideIf' );
197 v
= hideIfParse( $el
, spec
);
207 $fields
.on( 'change', func
);
212 }( mediaWiki
, jQuery
) );