PageSourceSearch

https://quote.goinsurance.com.au/index_files/jquery-autoclear.js

js goinsurance.com.au collected 2026-09-25 19:23:19 UTC 9,104 bytes, 255 lines download raw bytes

1/**
2 * Apply a helper value to text fields quickly & easily.
3 *
4 * The easiest way to use is $('your-selector').autoclear(). All the defaults
5 * in the settings object are used. For more advanced cases, and complete
6 * reference, @see http://www.mattlunn.me.uk/projects/autoclear
7 *
8 * @author Matt Lunn
9 * @version 7
10 * @param  Object / String
11 * @return Object jQuery
12 * @see http://www.mattlunn.me.uk/projects/autoclear
13 * @see README
14 */
15; (function ($) {
16    var slice = [].slice;
17    // Reference to the val function we will be extending
18    var _val = jQuery.fn.val;
19
20    /**
21     * The actual autoclear functionality
22     *
23     * @param  Object / String
24     * @return Object jQuery
25     * @see http://www.mattlunn.me.uk/projects/autoclear
26     * @see README
27     */
28    jQuery.fn.autoclear = function (options) {
29        var settings = {
30            defaultClass: 'default',
31            otherClass: 'other',
32            defaultValue: '',
33            useDefaultOnReset: true,
34            clearDefaultOnSubmit: true
35        };
36
37        if (arguments.length) {
38            switch (typeof options) {
39            case "string":
40                settings.defaultClass = options;
41            break;
42            case "object":
43                settings = jQuery.extend(settings, options);
44            break;
45            };
46        };
47
48        return this.bind({
49            'default.autoclear': function () {
50                var self = $(this).removeClass(settings.otherClass).
51                                   addClass(settings.defaultClass);
52
53                val(self, self.data('default.autoclear'));
54            },
55            'other.autoclear': function () {
56                var self = $(this);
57
58                self.removeClass(settings.defaultClass).
59                     addClass(settings.otherClass);
60            },
61            'focus.autoclear blur.autoclear': function (e) {
62                var handler = ((e.type === "focus") ? clearHelperIfShown
63                                                    : renderCorrectState);
64
65                handler(this);
66            }
67        }).each(function () {
68            // self caches $(this) for optimization
69            var self = $(this);
70            // The parent form of the input field.
71            var form = self.closest('form');
72            // The current value held by the input field
73            var currentValue = jQuery.trim(val(self));
74            // Holds the value chosen to show as the helper text
75            var defaultValue = self.attr('title');
76
77            // Calculate the actual defaultValue. If `title` is empty, we take
78            // the current value of the input field unless it's empty, in which
79            // case we fall back to the defaultValue in the settings object.
80            if (isBlank(defaultValue)) {
81                if (currentValue === '') {
82                    defaultValue = settings.defaultValue;
83                } else {
84                    defaultValue = currentValue;
85                };
86            };
87
88            // Set the default value
89            self.data('default.autoclear', defaultValue);			
90
91            // When resetting a form, is using useDefaultOnReset, we need to
92            // apply styles for default text; otherwise apply styles to what
93            // was shown on page load. We do this after a short timeout, to ensure
94            // the event was not actually cancelled by another hander.
95            form.bind('reset.autoclear', function (event) {
96                var e = event.originalEvent;
97                
98                setTimeout(function () {
99                  // Don't use event.isDefaultPrevented; the event object
100                  // we get passed will NOT be up-to-date if a delegate or live
101                  // bound handler cancels the event. jQuery.Event(e.origEvent)
102                  // is broken prior to 1.5, so don't use that either!
103                  // http://bugs.jquery.com/ticket/7793
104                  if (!(e.defaultPrevented || e.returnValue === false 
105                      || e.getPreventDefault && e.getPreventDefault())) {
106                      
107                    var expectedValue;
108
109                    if (settings.useDefaultOnReset) {
110                        expectedValue = '';
111                    } else {
112                        expectedValue = self.attr('defaultValue');
113                    };
114
115                    self.val(expectedValue);
116                  };
117                }, 0);
118            });
119
120            // If we have useDefaultOnReset, or there is no defaultValue,
121            // set the defaultValue to the helper text. This is so that if a
122            // form reset occurs, the intended value is set.
123            if (settings.useDefaultOnReset
124                || isBlank(jQuery.trim(self.attr('defaultValue')))) {
125
126                self.attr('defaultValue', defaultValue).val(currentValue);
127            };
128
129            // If we dont want to submit default values, we need to clear any
130            // helper values when the form is submitted. We set an immediate
131            // timeout to show the correct state again, incase the form
132            // submission is cancelled, and to make the page look nice whilst
133            // the POST is happening.
134            if (settings.clearDefaultOnSubmit) {
135                form.bind('submit.autoclear', function (event) {
136                    if (!event.isDefaultPrevented()) {
137                        clearHelperIfShown(self);
138
139                        setTimeout(function () {
140                          renderCorrectState(self);
141                        }, 0);
142                    };
143                });
144            };
145
146            // Intial setup of element.
147            renderCorrectState(this);
148        });
149    };
150
151    /**
152     * Extend the jQuery.fn.val function to apply the helper text automatically
153     * if the value is set to empty, and to automatically return an empty
154     * string if val() is called on an element showing the helper text.
155     *
156     * @see link		http://api.jquery.com/val
157     * @param Mixed		Any mixture of valid arguments for native val
158     * @return Mixed	Result of native val
159     */
160    jQuery.fn.val = function () {
161        var result = _val.apply(this, arguments);
162        var defaultValue;
163
164        // Getter
165        if (typeof result === "string") {
166            defaultValue = this.first().data    ('default.autoclear');
167
168            if (defaultValue !== undefined && result === defaultValue) {
169                result = '';
170            };
171        } else {
172        // Setter
173
174            this.each(function () {
175                var self = $(this);
176                var defaultValue = self.data('default.autoclear');
177
178                if (defaultValue !== undefined && self.val() === '') {
179                    self.trigger('default.autoclear');
180                } else {
181                    self.trigger('other.autoclear');
182                };
183            });
184        };
185
186        return result;
187    };
188
189    /**
190     * Helper function which detects whether the provided value is either
191     * undefined or an empty string.
192     *
193     * @param 	prop	String	Property to check
194     * @return	Boolean	Is it blank?
195     */
196    function isBlank (prop) {
197        return prop === undefined || prop === '';
198    };
199
200    /**
201     * Helper function that applies native jQuery val to provided object.
202     *
203     * @param el	Object	jQuery object to apply val to
204     * @param arg	Mixed	Optional: Parameter that will be passed to val
205     * @return Mixed		Result of applying val to the jQuery Object
206     */
207    function val (el) {
208        return _val.apply(el, slice.call(arguments, 1));
209    };
210
211    /**
212     * Helper function which will trigger the handlers bound to the
213     * "other.autoclear" event if the helper text is being displayed, or no
214     * value is being displayed. By default, autoclear binds a handler to
215     * "other.autoclear" which will remove the default class, show the other
216     * class, and set the element value to "".
217     *
218     * @param self  Object  Value accepted by jQuery constructor to select
219     *                      element to potentially clear.
220     * @return Object       jQuery object of "self".
221     */
222    function clearHelperIfShown (self) {
223        self = $(self);
224
225        if (self.val() === '') {
226            val(self, '').trigger('other.autoclear');
227        };
228
229        return self;
230    };
231
232    /**
233     * Helper function which will trigger the handlers bound to either the
234     * "default.autoclear" or "other.autoclear" events depending on whether the
235     * element provided contains a value or not.
236     *
237     * @param self  Object  Value accepted by jQuery constructor to select
238     *                      element to potentially clear.
239     * @return Object       jQuery object of "self".
240     */
241    function renderCorrectState (self) {
242        self = $(self);
243
244        var value = jQuery.trim(self.val());
245
246        if (value === '') {
247            self.trigger('default.autoclear');
248        } else {
249            self.trigger('other.autoclear');
250        };
251
252        return self;
253    };
254
255}(jQuery));

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.