0

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;
vitto
  • 19,094
  • 31
  • 91
  • 130

3 Answers3

4

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.

Felix
  • 88,392
  • 43
  • 149
  • 167
0

You should write .val('none'). The val method will find the <option> with that value. (Or, failing that, that text)

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
-1

Why clone it? As simple as it may be, I would define hidden html parts as string and simply append them:

var add = '<select>' +
          '  <option value="one">one</option>' +
          '  <option two ... '+
          '</select>';
$(something).appendTo(add);

Bit dirty, but... :) - (you could even define those hidden parts with asp/php, so you don't have to write each line)

Edit: already answered...

Adam Kiss
  • 11,811
  • 9
  • 48
  • 81