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>

3 Answers 3

3

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

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

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

demo

Reference:

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); 
                     });
2
  • Don't forget: stackoverflow.com/questions/742810/…
    – Johan
    Commented Sep 27, 2012 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). Commented Sep 27, 2012 at 19:40
1
$('<jquery selector criteria>').clone().attr("name", "new_name")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.