Subversion Repositories wpShopGermany4

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
5439 daniel 1
/*
2
 * Jeditable - jQuery in place edit plugin
3
 *
4
 * Copyright (c) 2006-2009 Mika Tuupola, Dylan Verheul
5
 *
6
 * Licensed under the MIT license:
7
 *   http://www.opensource.org/licenses/mit-license.php
8
 *
9
 * Project home:
10
 *   http://www.appelsiini.net/projects/jeditable
11
 *
12
 * Based on editable by Dylan Verheul <dylan_at_dyve.net>:
13
 *    http://www.dyve.net/jquery/?editable
14
 *
15
 */
16
 
17
/**
18
  * Version 1.7.1
19
  *
20
  * ** means there is basic unit tests for this parameter.
21
  *
22
  * @name  Jeditable
23
  * @type  jQuery
24
  * @param String  target             (POST) URL or function to send edited content to **
25
  * @param Hash    options            additional options
26
  * @param String  options[method]    method to use to send edited content (POST or PUT) **
27
  * @param Function options[callback] Function to run after submitting edited content **
28
  * @param String  options[name]      POST parameter name of edited content
29
  * @param String  options[id]        POST parameter name of edited div id
30
  * @param Hash    options[submitdata] Extra parameters to send when submitting edited content.
31
  * @param String  options[type]      text, textarea or select (or any 3rd party input type) **
32
  * @param Integer options[rows]      number of rows if using textarea **
33
  * @param Integer options[cols]      number of columns if using textarea **
34
  * @param Mixed   options[height]    'auto', 'none' or height in pixels **
35
  * @param Mixed   options[width]     'auto', 'none' or width in pixels **
36
  * @param String  options[loadurl]   URL to fetch input content before editing **
37
  * @param String  options[loadtype]  Request type for load url. Should be GET or POST.
38
  * @param String  options[loadtext]  Text to display while loading external content.
39
  * @param Mixed   options[loaddata]  Extra parameters to pass when fetching content before editing.
40
  * @param Mixed   options[data]      Or content given as paramameter. String or function.**
41
  * @param String  options[indicator] indicator html to show when saving
42
  * @param String  options[tooltip]   optional tooltip text via title attribute **
43
  * @param String  options[event]     jQuery event such as 'click' of 'dblclick' **
44
  * @param String  options[submit]    submit button value, empty means no button **
45
  * @param String  options[cancel]    cancel button value, empty means no button **
46
  * @param String  options[cssclass]  CSS class to apply to input form. 'inherit' to copy from parent. **
47
  * @param String  options[style]     Style to apply to input form 'inherit' to copy from parent. **
48
  * @param String  options[select]    true or false, when true text is highlighted ??
49
  * @param String  options[placeholder] Placeholder text or html to insert when element is empty. **
50
  * @param String  options[onblur]    'cancel', 'submit', 'ignore' or function ??
51
  *
52
  * @param Function options[onsubmit] function(settings, original) { ... } called before submit
53
  * @param Function options[onreset]  function(settings, original) { ... } called before reset
54
  * @param Function options[onerror]  function(settings, original, xhr) { ... } called on error
55
  *
56
  * @param Hash    options[ajaxoptions]  jQuery Ajax options. See docs.jquery.com.
57
  *
58
  */
59
 
60
(function($) {
61
 
62
    $.fn.editable = function(target, options) {
63
 
64
        if ('disable' == target) {
65
            $(this).data('disabled.editable', true);
66
            return;
67
        }
68
        if ('enable' == target) {
69
            $(this).data('disabled.editable', false);
70
            return;
71
        }
72
        if ('destroy' == target) {
73
            $(this)
74
                .unbind($(this).data('event.editable'))
75
                .removeData('disabled.editable')
76
                .removeData('event.editable');
77
            return;
78
        }
79
 
80
        var settings = $.extend({}, $.fn.editable.defaults, {target:target}, options);
81
 
82
        /* setup some functions */
83
        var plugin   = $.editable.types[settings.type].plugin || function() { };
84
        var submit   = $.editable.types[settings.type].submit || function() { };
85
        var buttons  = $.editable.types[settings.type].buttons
86
                    || $.editable.types['defaults'].buttons;
87
        var content  = $.editable.types[settings.type].content
88
                    || $.editable.types['defaults'].content;
89
        var element  = $.editable.types[settings.type].element
90
                    || $.editable.types['defaults'].element;
91
        var reset    = $.editable.types[settings.type].reset
92
                    || $.editable.types['defaults'].reset;
93
        var callback = settings.callback || function() { };
94
        var onedit   = settings.onedit   || function() { };
95
        var onsubmit = settings.onsubmit || function() { };
96
        var onreset  = settings.onreset  || function() { };
97
        var onerror  = settings.onerror  || reset;
98
        var json = false;
99
 
100
        /* show tooltip */
101
        if (settings.tooltip) {
102
            $(this).attr('title', settings.tooltip);
103
        }
104
 
105
        settings.autowidth  = 'auto' == settings.width;
106
        settings.autoheight = 'auto' == settings.height;
107
 
108
        return this.each(function() {
109
 
110
            /* save this to self because this changes when scope changes */
111
            var self = this;
112
 
113
            /* inlined block elements lose their width and height after first edit */
114
            /* save them for later use as workaround */
115
            var savedwidth  = $(self).width();
116
            var savedheight = $(self).height();
117
 
118
            /* save so it can be later used by $.editable('destroy') */
119
            $(this).data('event.editable', settings.event);
120
 
121
            /* if element is empty add something clickable (if requested) */
122
            if (!$.trim($(this).html())) {
123
                $(this).html(settings.placeholder);
124
            }
125
 
126
            $(this).bind(settings.event, function(e) {
127
 
128
                /* abort if disabled for this element */
129
                if (true === $(this).data('disabled.editable')) {
130
                    return;
131
                }
132
 
133
                /* prevent throwing an exeption if edit field is clicked again */
134
                if (self.editing) {
135
                    return;
136
                }
137
 
138
                /* abort if onedit hook returns false */
139
                if (false === onedit.apply(this, [settings, self])) {
140
                   return;
141
                }
142
 
143
                /* prevent default action and bubbling */
144
                e.preventDefault();
145
                e.stopPropagation();
146
 
147
                /* remove tooltip */
148
                if (settings.tooltip) {
149
                    $(self).removeAttr('title');
150
                }
151
 
152
                /* figure out how wide and tall we are, saved width and height */
153
                /* are workaround for http://dev.jquery.com/ticket/2190 */
154
                if (0 == $(self).width()) {
155
                    //$(self).css('visibility', 'hidden');
156
                    settings.width  = savedwidth;
157
                    settings.height = savedheight;
158
                } else {
159
                    if (settings.width != 'none') {
160
                        settings.width =
161
                            settings.autowidth ? $(self).width()  : settings.width;
162
                    }
163
                    if (settings.height != 'none') {
164
                        settings.height =
165
                            settings.autoheight ? $(self).height() : settings.height;
166
                    }
167
                }
168
                //$(this).css('visibility', '');
169
 
170
                /* remove placeholder text, replace is here because of IE */
171
                if ($(this).html().toLowerCase().replace(/(;|")/g, '') ==
172
                    settings.placeholder.toLowerCase().replace(/(;|")/g, '')) {
173
                        $(this).html('');
174
                }
175
 
176
                self.editing    = true;
177
                self.revert     = $(self).html();
178
                $(self).html('');
179
 
180
                /* create the form object */
181
                var form = $('<form />');
182
 
183
                /* apply css or style or both */
184
                if (settings.cssclass) {
185
                    if ('inherit' == settings.cssclass) {
186
                        form.attr('class', $(self).attr('class'));
187
                    } else {
188
                        form.attr('class', settings.cssclass);
189
                    }
190
                }
191
 
192
                if (settings.style) {
193
                    if ('inherit' == settings.style) {
194
                        form.attr('style', $(self).attr('style'));
195
                        /* IE needs the second line or display wont be inherited */
196
                        form.css('display', $(self).css('display'));
197
                    } else {
198
                        form.attr('style', settings.style);
199
                    }
200
                }
201
 
202
                /* add main input element to form and store it in input */
203
                var input = element.apply(form, [settings, self]);
204
 
205
                /* set input content via POST, GET, given data or existing value */
206
                var input_content;
207
 
208
                if (settings.loadurl) {
209
                    var t = setTimeout(function() {
210
                        input.disabled = true;
211
                        content.apply(form, [settings.loadtext, settings, self]);
212
                    }, 100);
213
 
214
                    var loaddata = {};
215
                    loaddata[settings.id] = self.id;
216
                    if ($.isFunction(settings.loaddata)) {
217
                        $.extend(loaddata, settings.loaddata.apply(self, [self.revert, settings]));
218
                    } else {
219
                        $.extend(loaddata, settings.loaddata);
220
                    }
221
                    $.ajax({
222
                       type : settings.loadtype,
223
                       url  : settings.loadurl,
224
                       data : loaddata,
225
                       async : false,
226
                       success: function(result) {
227
                          window.clearTimeout(t);
228
                          input_content = result;
229
                          input.disabled = false;
230
                       }
231
                    });
232
                } else if (settings.data) {
233
                    input_content = settings.data;
234
                    if ($.isFunction(settings.data)) {
235
                        input_content = settings.data.apply(self, [self.revert, settings]);
236
                    }
237
                } else {
238
                    input_content = self.revert;
239
                }
240
                content.apply(form, [input_content, settings, self]);
241
 
242
                input.attr('name', settings.name);
243
 
244
                /* add buttons to the form */
245
                buttons.apply(form, [settings, self]);
246
 
247
                /* add created form to self */
248
                $(self).append(form);
249
 
250
                /* attach 3rd party plugin if requested */
251
                plugin.apply(form, [settings, self]);
252
 
253
                /* focus to first visible form element */
254
                $(':input:visible:enabled:first', form).focus();
255
 
256
                /* highlight input contents when requested */
257
                if (settings.select) {
258
                    input.select();
259
                }
260
 
261
                /* discard changes if pressing esc */
262
                input.keydown(function(e) {
263
                    if (e.keyCode == 27) {
264
                        e.preventDefault();
265
                        //self.reset();
266
                        reset.apply(form, [settings, self]);
267
                    }
268
                });
269
 
270
                /* discard, submit or nothing with changes when clicking outside */
271
                /* do nothing is usable when navigating with tab */
272
                var t;
273
                if ('cancel' == settings.onblur) {
274
                    input.blur(function(e) {
275
                        /* prevent canceling if submit was clicked */
276
                        t = setTimeout(function() {
277
                            reset.apply(form, [settings, self]);
278
                        }, 500);
279
                    });
280
                } else if ('submit' == settings.onblur) {
281
                    input.blur(function(e) {
282
                        /* prevent double submit if submit was clicked */
283
                        t = setTimeout(function() {
284
                            form.submit();
285
                        }, 200);
286
                    });
287
                } else if ($.isFunction(settings.onblur)) {
288
                    input.blur(function(e) {
289
                        settings.onblur.apply(self, [input.val(), settings]);
290
                    });
291
                } else {
292
                    input.blur(function(e) {
293
                      /* TODO: maybe something here */
294
                    });
295
                }
296
 
297
                form.submit(function(e) {
298
 
299
                    if (t) {
300
                        clearTimeout(t);
301
                    }
302
 
303
                    /* do no submit */
304
                    e.preventDefault();
305
 
306
                    /* call before submit hook. */
307
                    /* if it returns false abort submitting */
308
                    if (false !== onsubmit.apply(form, [settings, self])) {
309
                        /* custom inputs call before submit hook. */
310
                        /* if it returns false abort submitting */
311
                        if (false !== submit.apply(form, [settings, self])) {
312
 
313
                          /* check if given target is function */
314
                          if ($.isFunction(settings.target)) {
315
                              var str = settings.target.apply(self, [input.val(), settings]);
316
                              $(self).html(str);
317
                              self.editing = false;
318
                              callback.apply(self, [self.innerHTML, settings]);
319
                              /* TODO: this is not dry */
320
                              if (!$.trim($(self).html())) {
321
                                  $(self).html(settings.placeholder);
322
                              }
323
                          } else {
324
                              /* add edited content and id of edited element to POST */
325
                              var submitdata = {};
326
                              submitdata[settings.name] = input.val();
327
                              submitdata[settings.id] = self.id;
328
                              /* add extra data to be POST:ed */
329
                              if ($.isFunction(settings.submitdata)) {
330
                                  $.extend(submitdata, settings.submitdata.apply(self, [self.revert, settings]));
331
                              } else {
332
                                  $.extend(submitdata, settings.submitdata);
333
                              }
334
 
335
                              /* quick and dirty PUT support */
336
                              if ('PUT' == settings.method) {
337
                                  submitdata['_method'] = 'put';
338
                              }
339
 
340
                              /* show the saving indicator */
341
                              $(self).html(settings.indicator);
342
 
343
                              /* defaults for ajaxoptions */
344
                              var ajaxoptions = {
345
                                  type    : 'POST',
346
                                  data    : submitdata,
347
                                  dataType: 'html',
348
                                  url     : settings.target,
349
                                  success : function(result, status) {
350
                                      if (ajaxoptions.dataType == 'html') {
351
                                        $(self).html(result);
352
                                        settings.data = result;
353
                                      }
354
                                      self.editing = false;
355
                                      callback.apply(self, [result, settings]);
356
                                      if (!$.trim($(self).html())) {
357
                                          $(self).html(settings.placeholder);
358
                                      }
359
                                  },
360
                                  error   : function(xhr, status, error) {
361
                                      onerror.apply(form, [settings, self, xhr]);
362
                                  }
363
                              };
364
 
365
                              /* override with what is given in settings.ajaxoptions */
366
                              $.extend(ajaxoptions, settings.ajaxoptions);
367
                              $.ajax(ajaxoptions);
368
 
369
                            }
370
                        }
371
                    }
372
 
373
                    /* show tooltip again */
374
                    $(self).attr('title', settings.tooltip);
375
 
376
                    return false;
377
                });
378
            });
379
 
380
            /* privileged methods */
381
            this.reset = function(form) {
382
                /* prevent calling reset twice when blurring */
383
                if (this.editing) {
384
                    /* before reset hook, if it returns false abort reseting */
385
                    if (false !== onreset.apply(form, [settings, self])) {
386
                        $(self).html(self.revert);
387
                        self.editing   = false;
388
                        if (!$.trim($(self).html())) {
389
                            $(self).html(settings.placeholder);
390
                        }
391
                        /* show tooltip again */
392
                        if (settings.tooltip) {
393
                            $(self).attr('title', settings.tooltip);
394
                        }
395
                    }
396
                }
397
            };
398
        });
399
 
400
    };
401
 
402
 
403
    $.editable = {
404
        types: {
405
            defaults: {
406
                element : function(settings, original) {
407
                    var input = $('<input type="hidden"></input>');
408
                    $(this).append(input);
409
                    return(input);
410
                },
411
                content : function(string, settings, original) {
412
                    $(':input:first', this).val(string);
413
                },
414
                reset : function(settings, original) {
415
                  original.reset(this);
416
                },
417
                buttons : function(settings, original) {
418
                    var form = this;
419
                    if (settings.submit) {
420
                        /* if given html string use that */
421
                        if (settings.submit.match(/>$/)) {
422
                            var submit = $(settings.submit).click(function() {
423
                                if (submit.attr("type") != "submit") {
424
                                    form.submit();
425
                                }
426
                            });
427
                        /* otherwise use button with given string as text */
428
                        } else {
429
                            var submit = $('<button class="button" type="submit" />');
430
                            submit.html(settings.submit);
431
                        }
432
                        $(this).append(submit);
433
                    }
434
                    if (settings.cancel) {
435
                        /* if given html string use that */
436
                        if (settings.cancel.match(/>$/)) {
437
                            var cancel = $(settings.cancel);
438
                        /* otherwise use button with given string as text */
439
                        } else {
440
                            var cancel = $('<button type="cancel" />');
441
                            cancel.html(settings.cancel);
442
                        }
443
                        $(this).append(cancel);
444
 
445
                        $(cancel).click(function(event) {
446
                            //original.reset();
447
                            if ($.isFunction($.editable.types[settings.type].reset)) {
448
                                var reset = $.editable.types[settings.type].reset;
449
                            } else {
450
                                var reset = $.editable.types['defaults'].reset;
451
                            }
452
                            reset.apply(form, [settings, original]);
453
                            return false;
454
                        });
455
                    }
456
                }
457
            },
458
            text: {
459
                element : function(settings, original) {
460
                    var input = $('<input />');
461
                    if (settings.width  != 'none') { input.width(settings.width);  }
462
                    if (settings.height != 'none') { input.height(settings.height); }
463
                    /* https://bugzilla.mozilla.org/show_bug.cgi?id=236791 */
464
                    //input[0].setAttribute('autocomplete','off');
465
                    input.attr('autocomplete','off');
466
                    $(this).append(input);
467
                    return(input);
468
                }
469
            },
470
            textarea: {
471
                element : function(settings, original) {
472
                    var textarea = $('<textarea />');
473
                    if (settings.rows) {
474
                        textarea.attr('rows', settings.rows);
475
                    } else if (settings.height != "none") {
476
                        textarea.height(settings.height);
477
                    }
478
                    if (settings.cols) {
479
                        textarea.attr('cols', settings.cols);
480
                    } else if (settings.width != "none") {
481
                        textarea.width(settings.width);
482
                    }
483
                    $(this).append(textarea);
484
                    return(textarea);
485
                }
486
            },
487
            select: {
488
               element : function(settings, original) {
489
                    var select = $('<select />');
490
                    $(this).append(select);
491
                    return(select);
492
                },
493
                content : function(data, settings, original) {
494
 
495
                	if (typeof settings.json == "undefined")
496
                	{
497
 
498
                		/* If it is string assume it is json. */
499
	                    if (String == data.constructor) {
500
	                        eval ('var json = ' + data);
501
	                    } else {
502
	                    /* Otherwise assume it is a hash already. */
503
	                        var json = data;
504
	                    }
505
 
506
	                    settings.json = json;
507
 
508
                	}
509
                	else
510
                	{
511
 
512
                		json = settings.json;
513
 
514
                	}
515
 
516
                    for (var key in json) {
517
                        if (!json.hasOwnProperty(key)) {
518
                            continue;
519
                        }
520
                        if ('selected' == key) {
521
                            continue;
522
                        }
523
 
524
                        if (typeof json[key]['name'] == 'string')
525
                        {
526
 
527
                        	var option = $('<optgroup />').attr('label', json[key]['name']);
528
 
529
                        	for (var key2 in json[key]['fields'])
530
                        	{
531
                        		option.append($('<option />').val(key2).append(json[key]['fields'][key2]));
532
                        	}
533
 
534
                        }
535
                        else
536
                        {
537
                        	var option = $('<option />').val(key).append(json[key]);
538
                        }
539
 
540
                        $('select', this).append(option);
541
                    }
542
                    /* Loop option again to set selected. IE needed this... */
543
                    $('select', this).find('option').each(function() {
544
                        if ($(this).val() == json['selected'] ||
545
                            $(this).text() == $.trim(original.revert)) {
546
                                $(this).attr('selected', 'selected');
547
                        }
548
                    });
549
                }
550
            }
551
        },
552
 
553
        /* Add new input type */
554
        addInputType: function(name, input) {
555
            $.editable.types[name] = input;
556
        }
557
    };
558
 
559
    // publicly accessible defaults
560
    $.fn.editable.defaults = {
561
        name       : 'value',
562
        id         : 'id',
563
        type       : 'text',
564
        width      : 'auto',
565
        height     : '25px',
566
        event      : 'click.editable',
567
        onblur     : 'cancel',
568
        loadtype   : 'GET',
569
        loadtext   : 'Loading...',
570
        placeholder: 'Click to edit',
571
        loaddata   : {},
572
        submitdata : {},
573
        ajaxoptions: {}
574
    };
575
 
576
})(jQuery);