0

I have an html dropdown :

<select name="name1">
<option value="1">John</option>
<option value="2">Doe</option>
<option value="3">Foo</option>
<option value="4">Bar</option>
</select>

Is there a jQuery function that generates the same options but a different dropdown name like:

<select name="name2">
<option value="1">John</option>
<option value="2">Doe</option>
<option value="3">Foo</option>
<option value="4">Bar</option>
</select>
Perroquiet
  • 177
  • 1
  • 2
  • 14

3 Answers3

3

Assuming that $place is where you want to append the new combobox.

$select = $('select').clone();

$place.append($select.attr('name', 'name2'));

demo

Reference:

Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82
2

Try cloning and changing the name,

var $newSelect = $('select[name=name1]').clone().attr('name', 'name2');

append/prepend the $newSelect to anywhere in your document :)

Also as David suggested you can dynamically generate the name using below approach,

var $newSelect = $('select[name=name1]')
                    .clone()
                    .attr('name', function(i,n) { 
                         var int = 
                                parseInt(n.match(/\d*/),10); 
                         return n.replace(/\d*/, int + 1); 
                     });
Community
  • 1
  • 1
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • Don't forget: http://stackoverflow.com/questions/742810/clone-isnt-cloning-select-values – Johan Sep 27 '12 at 19:39
  • 1
    Perhaps it's only true in this example, but, given that example, I'd suggest: `.attr('name', function(i,n) { var int = parseInt(n.match(/\d*/),10); return n.replace(/\d*/, int + 1); });` (that's untested, but *should* increment the number 'dynamically' rather than hard-coding it within the replacement string). – David Thomas Sep 27 '12 at 19:40
1
$('<jquery selector criteria>').clone().attr("name", "new_name")
ilan berci
  • 3,883
  • 1
  • 16
  • 21