csotelo
csotelo

Reputation: 1475

JQuery change selected value after clone dropdown

I have this dropdown. I need clone for my other dropdown lists:

<select name="general">
<option value="0" style="font-size:11px">Nothing</option>
<option class="dropdown_root" value="1">Admin</option>
<option class="dropdown_root_first_lvl" value="2">General</option>
<option class="dropdown_root_next_lvl" value="3">Group</option>
<option class="dropdown_root_next_lvl" value="4">Sales</option>
</select>

<select name="group">
</select>

My problem is I want to clone the same content but I want the value selected from the list "group" is "Group" ... whose value is 3

I tried this:

var new_dd = $('select[name="general"] option').clone();
new_dd.val('3').attr('selected','selected').appendTo('select[name="group"]');

but I find this:

<select name="group">
<option value="3" style="font-size:11px" selected="selected">Nothing</option>
<option class="dropdown_root" value="3" selected="selected">Admin</option>
<option class="dropdown_root_first_lvl" value="3" selected="selected">General</option>
<option class="dropdown_root_next_lvl" value="3" selected="selected">Group</option>
<option class="dropdown_root_next_lvl" value="3" selected="selected">Sales</option>
</select>

I want to see is:

<select name="group">
<option value="0" style="font-size:11px">Nothing</option>
<option class="dropdown_root" value="1">Admin</option>
<option class="dropdown_root_first_lvl" value="2">General</option>
<option class="dropdown_root_next_lvl" value="3" selected="selected">Group</option>
<option class="dropdown_root_next_lvl" value="4">Sales</option>
</select>

How could obtain this?

Upvotes: 0

Views: 3452

Answers (3)

mesimplybj
mesimplybj

Reputation: 639

HERE is a DEMO. http://jsfiddle.net/Simplybj/Eyq5x/

var new_dd = $('select[name="general"] option').clone();
new_dd.appendTo('select[name="group"]');
$('select[name="group"]').val( $('select[name="general"] option').eq(2).val() ).attr('selected',true);

Upvotes: 0

Ram
Ram

Reputation: 144659

try this:

$('select[name="general"] option').each(function(){
   $(this).clone().appendTo('select[name="general"]')
})

$('select[name="general"] option[value="3"]').prop("selected", true)

Upvotes: 2

thecodeparadox
thecodeparadox

Reputation: 87073

var new_dd = $('select[name="general"] option').clone();
new_dd
    .filter(function() { 
        return this.value == 3;  // filter for option with value=3
    }) // in this point I have only option with value=3
    .attr('selected', 'selected') // give selected to that option
    .end() // capture all options again
    .appendTo('select[name="group"]'); // append to target

DEMO

Upvotes: 3

Related Questions