Search code examples
javascriptdomclonenode

Why don't select and textarea value changes get updated upon cloning as with input elements?


In Firefox at least, when using cloneNode(true) on a dynamically or user-altered textarea or select element, the value property is not preserved (nor is the DOM altered to reflect dynamic changes), whereas with input elements, a change to the value property or by the user gets reflected in the DOM (so it is preserved upon the call to cloneNode). Why is there this distinction?

UPDATE:

  1. I meant to ask: Is this behavior prescribed in a spec somewhere? (or detailed in a bug report?)
  2. A sample is at: http://jsfiddle.net/9RSNt/1/

Solution

  • I suspect the difference arises because textarea and selects' values are determined by their node content. Modifying the control's value modifies their DOM properties, but not their node content, so when you clone them, the clone has the value of the original element.

    You can get around this by updating their node content on the change event:

    // textarea
    $("textarea").change(function() { $(this).text($(this).val()); });
    
    // select
    $("select").change(function() {
        var sel = $(this).children(":selected");
        $(this.children).not(sel).removeAttr("selected");
        sel.attr("selected", "selected");
    });
    

    http://jsfiddle.net/emr2w/8/

    EDIT:

    There are a number of Mozilla bug cases on this (some resolved and some not), but any mention of the actual specs are few and far between. It seems that the the behavior of the value property after a cloneNode() may be a gray area that is not clearly defined in the spec. After all, the purpose of cloneNode() is to clone a DOM node, and not necessarily its object state.

    https://bugzilla.mozilla.org/show_bug.cgi?id=197294
    https://bugzilla.mozilla.org/show_bug.cgi?id=230307
    https://bugzilla.mozilla.org/show_bug.cgi?id=237783