Can't .append() option to select element

蓝咒 提交于 2020-01-02 11:44:52

问题


I have a problem with .append() function.

$('#add_row').on('click', function(){
    var new_row = $(row_default).clone();
    new_row.find('.col-1').text($(this).find('.ass-col-partenza').text());
    new_row.find('.col-2').text($(this).find('.ass-col-colore').text());
    new_row.find('.col-3').empty().html($select.clone());
    $table.append(new_row);
    console.log('New row added with select: ', $select);
});

$('#add_option').on('click', function(){
    var option = $('<option/>').val('Value '+idx).text('Text '+idx);
    idx++;
    // This should add options, and they should be added to DOM in future .append()
    $select.append(option);
    $('#my_table').find('.my_select').append(option);
    console.log('Added new option, new select is: ',$select);
});

Here is the fiddle with a short instruction list: http://jsfiddle.net/v15zyzxj/5/

I would expect that if I append an option, this is shown if I append a new row.

PS I deleted my previous question because it was getting pretty messy.


回答1:


The new option element just created and added to $select is being removed and added to .my-select elements on the DOM. To avoid that, add a clone to $select as suggested below.

Just change:

$select.append(option);

To:

$select.append(option.clone());

DEMO

Alternatively you could use .add() to combine all elements (in DOM or memory) that you want to append the new option to and then just .append() without the need to .clone():

//$select.append(option);
$('#my_table').find('.my_select').add($select).append(option);

DEMO



来源:https://stackoverflow.com/questions/33350072/cant-append-option-to-select-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!