Help with copying a dropdown selection

Discussion in 'JavaScript' started by suami93, Dec 17, 2008.

  1. #1
    Hi,

    My code looks like this:

    <li id="id_5" value="5">
    <select id="cat_5" class="dropdown" name="cat_5">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
    <option value="4">four</option>
    <option value="5">five</option>
    <option value="6">six</option>
    <option selected="selected " value="7">seven</option></select>
    <li id="id_6" value="6">
    <select id="cat_6" class="dropdown" name="cat_6"/> </select>


    Now I would like to copy all 7 options into the new select (id="cat_6).
    Can someone please tell me how can I do that??

    Thanks in advance.
    suami.
     
    suami93, Dec 17, 2008 IP
  2. lp1051

    lp1051 Well-Known Member

    Messages:
    163
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    108
    #2
    Hi suami,
    I suppose, from your example, it should copy the options to cat_6 after you select one from cat_5, right?
    Then add onchange event here :
    <select id="cat_5" class="dropdown" name="cat_5" onchange="copyThem(this, 'cat_6')">

    And the function could be like this :

    function copyThem(from, to_id) {
    var ind = from.selectedIndex,
    to = document.getElementById(to_id),
    copy;
    for(var i=0; i<=ind; i++) {
    copy = from.options;
    to.options = new Option(copy.text, copy.value);
    }
    }

    It depends much on what you gonna do with it, because the example I gave you doesn't clean options in the cat_6 (when selecting option from cat_5 twice), it copies all options till and with the selected one...
    But I hope you can get some idea, how to adapt it to your needs.
     
    lp1051, Dec 17, 2008 IP