Search code examples
javascriptasp.net-mvc-3clonehtml.dropdownlistfor

MVC3: Use javascript to clone HTML elements that use models


Is it possible to use the Javascript method clone() to clone an mvc html element like dropdown list that is defined using a model?

I have a drop down list with options from a model; and I want to add a similar drop down list when the user clicks on a button. My drop down list is defined as

<div id="parent">
    <div id="id">
        @Html.DropDownListFor(m =>m.mymodel)
    </div>
</div>

I have added a code like this for my JS

var new = document.getElementById('id').cloneNode( true );
document.getElementById( 'parent' ).appendChild( new );

But this does not work. If I cannot use cloning, how else can i achieve this?


Solution

  • You can't use new as a variable name -- that's a reserved word in Javascript. Your approach should work, but just be aware that the id attribute has to be unique in an HTML document.