Cloning Select Inputs With jQuery April 4th, 2011
The Problem
The problem is that jQuery does not clone the selected option when cloning a select input (jQuery only deals with DOM elements). Assume the following HTML:
<form method="post" action=""> <fieldset> <div> <select name="names[]"> <option value="abe">Abe</option> <option value="bob">Bob</option> <option value="cam">Cam “My dad likes to shop me around” Newton</option> <option value="dom">Dom</option> <option value="eve">Eve</option> </select> <input type="button" value="Clone!" /> </div> </fieldset> </form>
If you select anything other than the first option, your clone will result in the incorrect option being selected after the clone. Attempting the following will fail:
$(document).ready(function() { $('input[type="button"]').live('click', function() { // The value of the select input var value = $(this).siblings('select').val(); // Our cloned object var obj = $(this).closest('div').clone(); // Try to set the value (this will not work) $(obj).find('select').val(value); // The parent fieldset var fieldset = $(this).closest('fieldset'); // Append our new object $(fieldset).append(obj); }); });
The Solution
There are a few ways to tackle this problem, however I found the following to be quite simple — set the value of the select after you insert the option back into the DOM.
$(document).ready(function() { $('input[type="button"]').live('click', function() { // The value of the select input var value = $(this).siblings('select').val(); // Our cloned object var obj = $(this).closest('div').clone(); // The parent fieldset var fieldset = $(this).closest('fieldset'); // Append our new object $(fieldset).append(obj); // Since we appended our new object, the last select object will be the one we just added $(fieldset).find('select:last').val(value); }); });
Example
Go ahead and try a demo:
Example of Cloning Select Inputs With jQuery Demoblog comments powered by Disqus