Search code examples
jqueryselectclone

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?


Solution

  • 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