Search code examples
jqueryattributesjquery-selectorshtml-manipulation

Jquery: Cloning a select list and selecting an option by its value


I'm trying to append a select option list to a div table with jQuery, after done this, I'd like to select a specific option of the list, I'm trying something like this:

// my hidden option list
<div style="display:none;">
<select class="option_list">
    <option value="male">Male</option>
    <option value="female">Female</option>
    <option value="none">Unknown</option>
</select>
</div>

<div id="my_table">
    <div>
        <div>John</div>
        <div>25</div>
        <div></div>
    </div>
    <div>
        <div>Emy</div>
        <div>22</div>
        <div></div>
    </div>
    <div>
        <div>Sarah</div>
        <div>28</div>
        <div></div>
    </div>
</div>

// $(".option_list") is hidden in HTML page, I clone and append it to my div table row
$(".option_list")
      .clone ()
      .appendTo ("#my_table > div > div:last-child")
      .attr ("name", "a_dynamic_name_for_php_form")
      .find ("option[value=none]").selected = true;

Solution

  • Try this:

    $(".option_list")
      .clone ()
      .appendTo ("#my_table > div > div:last-child")
      .attr ("name", "a_dynamic_name_for_php_form")
      .find ("option[value=none]").attr("selected", "true");
    

    Notice the change in the last line.