Can't .append() option to select

1.6k views Asked by At

I have a problem with .append() function. I created a <select/> element in jquery, and I'm appending it to many table rows, with (sample classes):

var $select = $('<select class="my-select" ><option></option></select>');
$('‪#‎mytable‬ tr.first_row td.first_cell').append($select.clone());
$('‪#‎mytable‬ tr.second_row td.first_cell').append($select.clone());

then, I want to add a new <option/> to that select, so I do like this:

var new_option = $('<option/>').val('value').text('text');
$('.my-select').append(new_option); //works
$select.append(new_option); //doesn't work

Everything works fine, the select is added to any table row, and the new_option is appended to any of those <select>, but I can't append it to the $select element.... I tried in many ways but it seems impossible... I also tried:

$select.find('option:last').after(new_option); //doesn't work
$select.find('option:last').before(new_option); //doesn't work
new_option.appendTo($select); //doesn't work

Here is the fiddle http://jsfiddle.net/v15zyzxj/4/

Anyone has any idea why this should not work? It looks like something extremely easy, but I can't sort this problem out, I hope someone can help me understand what's going on..

2

There are 2 answers

5
PeterKA On BEST ANSWER

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

10
guest271314 On

Appear to append at stacksnippets

var $select = $('<select class="my-select" ><option></option></select>');
// define variable `clone`
var clone = $select.clone();
var new_option = $('<option/>').val('value').text('text');
$select.append(new_option); 

$("body").append($select);

var new_option2 = $('<option/>').val('value').text('text2');
clone.append(new_option2);
$("table tr").append(clone);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody>
  <tr></tr>
    </tbody>
</table>