Clone (Copy) Dropdown List with Selected Value using jQuery

27 Aug 2014  
5388 Views

Here Mudassar Ahmed Khan has provided a code snippet to clone or copy a HTML Select DropDown List items on Button click using jQuery. The DropDown List items are cloned along with the Selected Value.

This code snippet is to clone or copy a HTML Select DropDown List items on Button click using jQuery. The DropDown List items are cloned along with the Selected Value.
<select name=”ddlFruits” id=”ddlFruits”>
    <option value=”0″>Please Select</option>
    <option value=”1″>Mango</option>
    <option value=”2″>Apple</option>
    <option value=”3″>Banana</option>
    <option value=”4″>Orange</option>
</select>
<br />
<br />
<input type=”button” id=”btnClone” value=”Clone” />
<hr />
    $(function () {
        $(“#btnClone”).bind(“click”, function () {
            var index = $(“#container select”).length + 1;
            //Clone the DropDownList
            var ddl = $(“#ddlFruits”).clone();
            //Set the ID and Name
            ddl.attr(“id”, “ddlFruits_” + index);
            ddl.attr(“name”, “ddlFruits_” + index);
            //[OPTIONAL] Copy the selected value
            var selectedValue = $(“#ddlFruits option:selected”).val();
            ddl.find(“option[value = ‘” + selectedValue + “‘]”).attr(“selected”, “selected”);
            //Append to the DIV.
            $(“#container”).append(ddl);
            $(“#container”).append(“

“);

        });
    });
Explanation
There’s an HTML DropDown (SELECT element) and a Button. To the Button I have assigned a jQuery Click event handler.
When the Button is clicked, the HTML DropDown List items are cloned (copied) and a new HTML DropDown is appended to the HTML DIV.
Demo
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: