jquery.fix.clone.js 1.4 KB

1234567891011121314151617181920212223242526
  1. // Textarea and select clone() bug workaround | Spencer Tipping
  2. // Licensed under the terms of the MIT source code license
  3. // Motivation.
  4. // jQuery's clone() method works in most cases, but it fails to copy the value of textareas and select elements. This patch replaces jQuery's clone() method with a wrapper that fills in the
  5. // values after the fact.
  6. // An interesting error case submitted by Piotr Przybył: If two <select> options had the same value, the clone() method would select the wrong one in the cloned box. The fix, suggested by Piotr
  7. // and implemented here, is to use the selectedIndex property on the <select> box itself rather than relying on jQuery's value-based val().
  8. (function (original) {
  9. jQuery.fn.clone = function () {
  10. var result = original.apply(this, arguments),
  11. my_textareas = this.find('textarea').add(this.filter('textarea')),
  12. result_textareas = result.find('textarea').add(result.filter('textarea')),
  13. my_selects = this.find('select').add(this.filter('select')),
  14. result_selects = result.find('select').add(result.filter('select'));
  15. for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
  16. for (var i = 0, l = my_selects.length; i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;
  17. return result;
  18. };
  19. }) (jQuery.fn.clone);
  20. // Generated by SDoc