JQuery clone не копирует selected options

Столкнулся с интересной “особенностью” - JQuery clone при копировании полей форм не сохраняет выбранные значения Select. Помогает гуглопоиск по соответствующей формулировке. Как выяснилось, с копированием значений полей форм input, textarea и других

#3016 (Textarea loses current value when cloned)
jquery clone doesn’t copy selected value

“Подручное” решение, помогающее перенести значения в новые select-ы..

var selects = $(cloneSourceId).find("select");
$(selects).each(function(i) {
var select = this;
$(clone).find("select").eq(i).val($(select).val());
});

Или “доработка” штатного jquery.clone


// Textarea and select clone() bug workaround | Spencer Tipping
// Licensed under the terms of the MIT source code license
//
// Motivation.
// 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
// values after the fact.
//
// An interesting error case submitted by Piotr Przybyl: 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 // and implemented here, is to use the selectedIndex property on the </select> box itself rather than relying on jQuery's value-based val().
//
(function (original) {
jQuery.fn.clone = function () {
var result = original.apply(this, arguments),
my_textareas = this.find('textarea').add(this.filter('textarea')),
result_textareas = result.find('textarea').add(result.filter('textarea')),
my_selects = this.find('select').add(this.filter('select')),
result_selects = result.find('select').add(result.filter('select'));
//
for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
for (var i = 0, l = my_selects.length; i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;
//
return result;
};
}) (jQuery.fn.clone)

Метки:

Автор будет признателен, если Вы поделитесь ссылкой на статью, которая Вам помогла:
BB-код (для вставки на форум)

html-код (для вставки в ЖЖ, WP, blogger и на страницы сайта)

ссылка (для отправки по почте)

1 комментарий к записи “JQuery clone не копирует selected options”

  1. Alexey сообщает :

    Доброго дня.
    Если перед клонированием для select пройтись и выставить у option selected, то все клонируется как нужно и бубен не нужно трясти:
    .find(’select option:selected’).attr(’selected’,’selected’)

Добавить комментарий