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...
精彩评论