问题描述:

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;

网友答案:

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.

网友答案:

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

网友答案:

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...

相关阅读:
Top