-
Notifications
You must be signed in to change notification settings - Fork 0
/
gemini.form.js
936 lines (800 loc) · 26.5 KB
/
gemini.form.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
/* global Templates */
/**
* @fileoverview
A Gemini plugin that can validate forms on the front-end as well as submit them
using ajax.
### Notes
- The plugin follows the [JSend standard](http://labs.omniti.com/labs/jsend).
- Alerted results are generated using an [alert template](https://github.com/carpages/gemini-form/blob/master/templates/alert.hbs)
- The form's action is used to make the ajax request
- You can specify where the result is targeted per input using `data-form-alert`
*
* @namespace gemini.form
* @copyright Carpages.ca 2014
* @author Matt Rose <[email protected]>
*
* @requires gemini
*
* @prop {function} onSubmit {@link gemini.form#onSubmit}
* @prop {function} onResponse {@link gemini.form#onResponse}
* @prop {string} formAlertTarget {@link gemini.form#formAlertTarget}
* @prop {object} customTests {@link gemini.form#customTests}
* @prop {function} defaultTest {@link gemini.form#defaultTest}
* @prop {object} templates {@link gemini.form#templates}
* @prop {object} customResponseHandlers {@link gemini.form#customResponseHandlers}
* @prop {object} disableBuiltInResponseHandlers {@link gemini.form#disableBuiltInResponseHandlers}
*
* @example
<html>
<form id="js-ajax-form" action="http://fake.carpages.ca/ajax/url/" method="post">
<div>
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
</div>
<div>
<label for="select-choice">Select Dropdown Choice:</label>
<select name="select-choice" id="select-choice">
<option value="Choice 1">Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
</select>
</div>
<div>
<label for="textarea">Textarea:</label>
<textarea cols="40" rows="8" name="textarea" id="textarea"></textarea>
</div>
<label>
<input type="checkbox" name="checkbox" id="checkbox" />
Checkbox
</label>
<input class="button" type="submit" value="Submit" />
</form>
</html>
*
* @example
G('#js-ajax-form').form();
*/
( function( factory ) {
if ( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define([ 'gemini', 'gemini.form.templates' ], factory );
} else if ( typeof exports === 'object' ) {
// Node/CommonJS
module.exports = factory( require( 'gemini-loader' ), require( './templates.js' ));
} else {
// Browser globals
factory( G, Templates.Default.Form );
}
})( function( $, T ) {
$.boiler( 'form', {
defaults: {
/**
* Whether to send ajax request
*
* @name gemini.form#ajax
* @type boolean
* @default true
*/
ajax: true,
/**
* Additional ajax options to pass to the jQuery ajax call.
* Overrides defaults.
*
* @name gemini.form#ajax
* @type object
* @default {}
*/
ajaxOptions: {},
/**
* Callback function after the user has submitted the form
*
* @name gemini.form#onSubmit
* @type function
* @default false
*/
onSubmit: false,
/**
* Callback function after the server has returned a response
*
* @name gemini.form#onResponse
* @param {jqXHR} jqXHR The XHR object from the AJAX request.
* @param {string} textStatus The status of the AJAX response.
* @type function
* @default false
*/
onResponse: false,
/**
* Selector of container for the form alert message
*
* *Note:* By default, it asserts it before the submit buttons
*
* @name gemini.form#formAlertTarget
* @type string
* @default false
*/
formAlertTarget: false,
/**
* Selector of container for the input alert message
*
* *Note:* By default, it asserts it after the input itself
*
* @name gemini.form#inputAlertTarget
* @type string
* @default false
*/
inputAlertTarget: false,
/**
* Selector of parent for the input alert container
*
* @name gemini.form#inputAlertParent
* @type string
* @default ''
*/
inputAlertParent: '',
/**
* Determines whether server validation errors should be shown on the
* coordinating input, or only in the form alert bucket.
*
* @name gemini.form#showServerValidationErrorOnInput
* @type boolean
* @default false
*/
showServerValidationErrorOnInput: false,
/**
* Determines the class that gets added to the submit button when ajax
* is true and the form is submitting.
*
* @name gemini.form#loadingButtonClass
* @type string
* @default 'is-loading'
*/
loadingButtonClass: 'is-loading',
/**
* Allows passing of custom messages to show for different form states.
*
* @name gemini.form#messages
* @type object
* @default {
* submittingTitle: 'Submitting',
* localValidationFail: 'There are errors with your form submission. Please see below.',
* requiredField: 'This field is required',
* serverValidationFail: 'Please correct the following:',
* success: 'Your message was successfully sent.',
* imageTooLargeError: 'The image you are trying to upload is too large. Try again with a smaller image.',
* fallbackError: 'Something went wrong. Please try again later. Sorry for any inconvenience.'
* }
*/
messages: {},
/**
* The CSS module names associated with a node type. This module
* is passed to the template
*
* @name gemini.form#moduleNames
* @type object
* @default {
* "default": "alert",
* "input": "alert-input",
* "form": "alert-form"
* }
*/
moduleNames: {
default: 'alert',
input: 'alert-input',
form: 'alert-form'
},
/**
* The CSS class to be added to the input that has an error.
*
* @name gemini.form#errorClass
* @type string
* @default 'is-error'
*/
errorClass: 'is-error',
/**
* Whether or not select dropdowns are wrapped with a styling div
*
* @name gemini.form#selectWrapper
* @type boolean
* @default false
*/
selectWrapper: false,
/**
* The class of the select wrapping div
*
* @name gemini.form#selectWrapperClass
* @type string
* @default '.select'
*/
selectWrapperClass: '.select',
/**
* The event associated with a node type. This event is bound on errors.
*
* @name gemini.form#eventTypes
* @type object
* @default {
* "default": "change",
* "input": "keyup"
* }
*/
eventTypes: {
default: 'change',
input: 'keyup'
},
/**
* If true, will try to use FormData to upload form data with a file input.
*
* @name gemini.form#supportFileUpload
* @type boolean
* @default false
*/
supportFileUpload: false,
/**
* Map of selectors pointing to functions for writing custom tests. These
* functions can either return boolean for pass or fail, or a data object
* that will be passed to the alert function.
*
* @name gemini.form#customTests
* @type object
* @default {}
*/
customTests: {},
/**
* The default test that runs for input objects. It can return either a
* boolean, or an object to be passed to the alert template
*
* @name gemini.form#defaultTest
* @type function
* @default return !!$(this).val();
*/
defaultTest: function() {
return !!$( this ).val();
},
/**
* An object of custom response handlers for handling your own responses
* from the server.
*
* Expects functions that get passed the response data.
* Expected keys:
* - response: Overall response handler. Overwrites entire built-in
* response handler.
* The following do not affect built-in handling of responses. They
* instead get called alongside the built-in handling. You can disable
* built-in handling of responses by setting the disable flags described below.
* - success: Success status response handler.
* - fail: Validation fail status response handler.
* - error: Error status response handler.
* - fallback: Fallback response handler when unhandled status is
* received from server.
*
* @name gemini.form#customResponseHandlers
* @type object
* @default {}
*/
customResponseHandlers: {
/**
* A function that allows you to take full control of what happens when
* the ajax response comes back. This function gets passed the response
* data from the server.
*
* @name gemini.form#customResponseHandlers.response
* @type function
* @default false
*/
response: false,
/**
* A function that allows you to take full control of what happens when
* the ajax response comes back with a success status. This function gets
* passed the response data from the server.
*
* @name gemini.form#customResponseHandlers.success
* @type function
* @default false
*/
success: false,
/**
* A function that allows you to take full control of what happens when
* the ajax response comes back with validation errors. This function gets
* passed the response data from the server.
*
* @name gemini.form#customResponseHandlers.fail
* @type function
* @default false
*/
fail: false,
/**
* A function that allows you to take full control of what happens when
* the ajax response comes back with a server error. This function gets
* passed the response data from the server.
*
* @name gemini.form#customResponseHandlers.error
* @type function
* @default false
*/
error: false,
/**
* A function that allows you to take full control of what happens when
* the ajax response comes back with a status other than 'success', 'fail',
* or 'error'. This function gets passed the response data from the server.
*
* @name gemini.form#customResponseHandlers.fallback
* @type function
* @default false
*/
fallback: false
},
/**
* An object that has keys to disable built-in handling of AJAX
* server responses.
*
* @name gemini.form#disableBuiltInResponseHandlers
* @type object
* @default {}
*/
disableBuiltInResponseHandlers: {
success: false,
fail: false,
error: false,
fallback: false,
all: false
},
/**
* Precompiled Handlebar templates to replace default.
* Expecting 'alert' for the alert message.
*
* @name gemini.form#templates
* @type object
* @default {}
*/
templates: {}
},
defaultMessages: {
submittingTitle: 'Submitting',
localValidationFail: 'There are errors with your form submission. Please see below.',
requiredField: 'This field is required',
serverValidationFail: 'Please correct the following:',
success: 'Your message was successfully sent.',
imageTooLargeError:
'The image you are trying to upload is too large. Try again with a smaller image.',
fallbackError: 'Something went wrong. Please try again later. Sorry for any inconvenience.'
},
lifecycleHooks: {},
init: function() {
var plugin = this;
// extend the templates
plugin.T = $.extend({}, T, plugin.settings.templates );
plugin.lifecycleHooks = $.extend(
{},
{
response: [],
success: [],
fail: [],
error: [],
fallback: []
},
plugin.settings.lifecycleHooks
);
// cache
plugin.$submit = plugin.$el.find( '[type="submit"]' );
plugin.submitTitle = plugin.$submit.text();
plugin.messages = $.extend({}, plugin.defaultMessages, plugin.settings.messages );
// cache requirements and their tests
plugin.requirements = [];
plugin.configureValidations();
// user has set custom form alert target
if ( plugin.settings.formAlertTarget ) {
var $formAlertTarget = plugin.$el.find( plugin.settings.formAlertTarget );
plugin.$el.data( 'form-alert-cache', $formAlertTarget );
if ( $formAlertTarget.children().length === 0 ) {
$formAlertTarget.hide();
}
}
// user has set custom input alert target
if ( plugin.settings.inputAlertTarget ) {
var $inputAlerts = plugin.$el.find( plugin.settings.inputAlertTarget );
$.each( $inputAlerts, function() {
var $inputAlert = $( this );
if ( $inputAlert.children().length < 1 ) {
$inputAlert.hide();
}
});
}
// use button click to byPass default submit
plugin.$submit.click( function( e ) {
e.preventDefault();
plugin._onSubmit();
});
},
configureValidations: function() {
var plugin = this;
$.each( plugin.settings.customTests, function( key, value ) {
$( key ).each( function() {
plugin.addValidation( this, value );
});
});
plugin.$el.find( '[required]' ).each( function() {
plugin.addRequiredValidation( this );
});
},
addValidation: function( el, testFn ) {
var plugin = this;
$( el ).data( 'usesCustomTest', true );
plugin.addRequirement({
el: el,
test: testFn
});
},
addRequiredValidation: function( el ) {
var plugin = this;
if ( !$( el ).data( 'usesCustomTest' )) {
plugin.addRequirement({
el: el,
test: plugin.settings.defaultTest
});
}
},
addRequirement: function( req ) {
var plugin = this;
var eventType =
plugin.settings.eventTypes[req.el.nodeName.toLowerCase()] ||
plugin.settings.eventTypes['default'];
req.eventName = eventType + '.geminiform';
req.$el = $( req.el );
plugin.requirements.push( req );
},
addLifecycleHook: function( lifecycleEvent, callback ) {
var plugin = this;
if ( typeof callback !== 'function' ) {
return;
}
plugin.lifecycleHooks[lifecycleEvent].push( callback );
return plugin;
},
_runLifecycleHooks: function( lifecycleEvent, response ) {
var plugin = this;
var fallbackLifecycleHooks = plugin.lifecycleHooks[lifecycleEvent];
if ( fallbackLifecycleHooks.length > 0 ) {
$.each( fallbackLifecycleHooks, function( _index, callback ) {
callback.call( plugin, response );
});
}
},
/**
* Callback function when the user submits the form
*
* @private
* @method
* @name gemini.form#_onSubmit
* @param {object} e Event object
**/
_onSubmit: function() {
var plugin = this;
if ( plugin.settings.onSubmit ) plugin.settings.onSubmit.call( plugin );
var validationStatus = ( plugin.validationStatus = plugin._checkRequirements());
// meets requirements
if ( validationStatus.pass ) {
if ( plugin.settings.ajax ) {
plugin._setSubmitting( true );
var data = plugin._getFormData();
var ajaxOptions = $.extend(
{},
{
url: plugin.$el.attr( 'action' ),
data: data,
type: 'POST',
dataType: 'json',
error: plugin._handleResponse.bind( plugin ),
success: plugin._handleResponse.bind( plugin ),
complete: function( jqXHR, textStatus ) {
if ( plugin.settings.onResponse ) {
plugin.settings.onResponse.call( plugin, jqXHR, textStatus );
}
plugin._setSubmitting( false );
}
},
plugin.settings.ajaxOptions
);
if ( plugin.settings.supportFileUpload ) {
ajaxOptions.processData = false;
ajaxOptions.contentType = false;
}
// Use ajax
$.ajax( ajaxOptions );
} else {
// Don't use ajax
plugin.$el.submit();
}
} else {
plugin._handleResponse({
status: 'error',
message: plugin.messages.localValidationFail
});
}
},
_getFormData: function() {
var plugin = this;
if ( plugin.settings.supportFileUpload && typeof FormData === 'function' ) {
var formData = new FormData( plugin.el );
return formData;
}
return plugin.$el.serialize();
},
_setSubmitting: function( isSubmitting ) {
var plugin = this;
var loadingClass = plugin.settings.loadingButtonClass;
plugin.submitting = isSubmitting;
if ( plugin.submitting ) {
// Disable submit button while ajax-ing
plugin.$submit
.prop( 'disabled', true )
.text( plugin.messages.submittingTitle )
.addClass( loadingClass );
} else {
// Reenable submit button when complete
plugin.$submit
.prop( 'disabled', false )
.text( plugin.submitTitle )
.removeClass( loadingClass );
}
},
/**
* Check if the form requirements pass
*
* @private
* @method
* @name gemini.form#_checkRequirements
* @return {array} Whether the requirements pass or not
**/
_checkRequirements: function() {
var plugin = this;
var pass = true;
var failedInputs = {};
$.each( plugin.requirements, function( i, requirement ) {
var thisPasses = plugin._checkInput( requirement.el, requirement.test );
if ( !thisPasses ) {
var failedInputSelector = '[name="' + requirement.el.name + '"]';
failedInputs[failedInputSelector] = requirement.el;
// Add change listener if failed
requirement.$el.on( requirement.eventName, function() {
var secondPass = plugin._checkInput( requirement.el, requirement.test );
if ( secondPass ) {
delete failedInputs[failedInputSelector];
requirement.$el.off( requirement.eventName );
}
});
}
pass = pass && thisPasses;
});
return {
pass: pass,
failedInputs: failedInputs
};
},
/**
* Check if a specific input has a value and append alert if it doesn't
*
* @private
* @method
* @name gemini.form#_checkInput
* @param {object} el The element that you're checking
* @return {boolean} Whether the input has a value or not
**/
_checkInput: function( el, test ) {
var plugin = this;
var $el = $( el );
// Default test
if ( typeof test === 'undefined' || !test ) {
test = plugin.settings.defaultTest;
}
var results = test.call( el );
// If results is false, or object
if ( !results || typeof results === 'object' ) {
// Create alert using results object with fallback
plugin.alert(
results || {
message: plugin.messages.requiredField
},
el
);
if ( $el.is( 'select' ) && plugin.settings.selectWrapper ) {
$el.parent( plugin.settings.selectWrapperClass ).addClass( plugin.settings.errorClass );
} else {
// Set status
$el.addClass( plugin.settings.errorClass );
}
return false;
} else {
// Remove alert
plugin.alert( false, el );
if ( $el.is( 'select' ) && plugin.settings.selectWrapper ) {
$el.parent( plugin.settings.selectWrapperClass ).removeClass( plugin.settings.errorClass );
} else {
// Remove status
$el.removeClass( plugin.settings.errorClass );
}
return true;
}
},
/**
* Handles the response from the server when the form is sent
*
* @private
* @method
* @name gemini.form#_handleResponse
* @param {object} response The ajax object returned from the server
**/
_handleResponse: function( response ) {
var plugin = this;
var customHandlers = plugin.settings.customResponseHandlers;
var disabledHandlers = plugin.settings.disableBuiltInResponseHandlers;
plugin._runLifecycleHooks( 'response', response );
if ( typeof customHandlers.response === 'function' ) {
customHandlers.response.call( plugin, response );
} else {
// Ajax request based on JSON standard http://labs.omniti.com/labs/jsend
switch ( response.status ) {
// when call is successful
case 'success':
if ( typeof customHandlers.success === 'function' ) {
customHandlers.success.call( plugin, response );
}
if ( disabledHandlers.success || disabledHandlers.all ) {
return;
}
plugin._runLifecycleHooks( 'success', response );
plugin._defaultSuccessHandler( response );
break;
// when call is rejected due to invalid data or call conditions
case 'fail':
if ( typeof customHandlers.fail === 'function' ) {
customHandlers.fail.call( plugin, response );
}
if ( disabledHandlers.fail || disabledHandlers.all ) {
return;
}
plugin._runLifecycleHooks( 'fail', response );
plugin._defaultFailHandler( response );
break;
// when call fails due to an error on the server
case 'error':
if ( typeof customHandlers.error === 'function' ) {
customHandlers.error.call( plugin, response );
}
if ( disabledHandlers.error || disabledHandlers.all ) {
return;
}
plugin._runLifecycleHooks( 'error', response );
plugin._defaultErrorHandler( response );
break;
// when server doesn't pass right data
default:
if ( typeof customHandlers.fallback === 'function' ) {
customHandlers.fallback.call( plugin, response );
}
if ( disabledHandlers.fallback || disabledHandlers.all ) {
return;
}
plugin._runLifecycleHooks( 'fallback', response );
plugin._defaultFallbackHandler( response );
}
}
},
_defaultSuccessHandler: function( response ) {
var plugin = this;
plugin.alert({
success: true,
message: plugin.messages.success
});
plugin.el.reset();
},
_defaultErrorHandler: function( response ) {
var plugin = this;
plugin.alert({
message: response.message
});
},
_defaultFailHandler: function( response ) {
var plugin = this;
plugin.alert({
message: plugin.messages.serverValidationFail,
errors: response.data
});
if ( plugin.settings.showServerValidationErrorOnInput ) {
var errors = response.data;
Object.keys( errors ).map( function( inputName ) {
var $inputEl = G( '[name*="' + inputName + '"]' );
plugin.alert(
{
message: errors[inputName]
},
$inputEl[0]
);
});
}
},
_defaultFallbackHandler: function( response ) {
var plugin = this;
if ( plugin.settings.supportFileUpload && response.status === 413 ) {
plugin.alert({
message: plugin.messages.imageTooLargeError
});
return;
}
plugin.alert({
message: plugin.messages.fallbackError
});
},
/**
* Alerts the user with a message
*
* @method
* @name gemini.form#alert
* @param {object} data The data to send to the alert template
**/
alert: function( data, el ) {
var plugin = this;
var isEl = typeof el !== 'undefined';
var isForm = !isEl;
if ( isForm ) {
plugin._formAlert( data );
} else {
plugin._inputAlert( data, el );
}
},
_formAlert: function( data ) {
var plugin = this;
var $el = plugin.$el;
var el = plugin.$el[0];
var $alertParent = $el.find( plugin.settings.formAlertTarget );
var $alert = plugin._getCachedAlert( $el );
if ( $alertParent ) {
// insert into input alert target when set
$alertParent.append( $alert );
} else {
// prepend button for form
plugin.$submit.before( $alert );
}
plugin._showAlertOrHide( $alert, data, el );
},
_inputAlert: function( data, el ) {
var plugin = this;
var $el = $( el );
var $alertParent = $el.closest( plugin.settings.inputAlertParent );
var $alertTarget = $alertParent.find( plugin.settings.inputAlertTarget );
var $alert = plugin._getCachedAlert( $alertTarget );
if ( $alertTarget ) {
// insert into input alert target when set
$alertTarget.append( $alert );
} else {
// append for input
$el.after( $alert );
}
plugin._showAlertOrHide( $alertTarget, data, el );
},
_getCachedAlert: function( $el ) {
var plugin = this;
var $cachedAlert = $el.data( 'form-alert-cache' );
if ( $cachedAlert ) return $cachedAlert;
// cache alert if it doesn't exist yet
var id = $el.data( 'form-alert' );
// grab set id, or generate new div
var $alert = id ? plugin.$el.find( id ) : $( '<div>' );
$el.data( 'form-alert-cache', $alert );
return $alert;
},
_showAlertOrHide: function( $alert, data, el ) {
var plugin = this;
// show alert if successful
if ( data ) {
data.module =
plugin.settings.moduleNames[el.nodeName.toLowerCase()] ||
plugin.settings.moduleNames['default'];
$alert.html( plugin.T.alert( data )).show();
} else {
$alert.hide();
}
}
});
// Return the jquery object
// This way you don't need to require both jquery and the plugin
return $;
});