jquery.jeditable.js 23 KB

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