user3584923 user3584923 - 2 months ago 8
jQuery Question

text string from table add to select option with jquery

I have select with some option:

<select class="mat">
<option value="0">mat 1</option>
</select>


and table:

<table id="mat-table">
<tr>
<td>option 1</td>
<td>desc</td>
</tr>
<tr>
<td>option 2</td>
<td>desc</td>
</tr>
<tr>
<td>option 3</td>
<td>desc</td>
</tr>
</table>


I want with jquery copy text 'option 1', 'option 2' from this table to select option and get this:

<select class="mat">
<option value="0">option 1</option>
<option value="1">option 2</option>
<option value="2">option 3</option>
</select>


please help

Answer

Try this:

$('#mat-table td:first-child').each(function(i) {
    var $option = $('<option>', { value: i }).text(this.textContent);
    $('.mat').append($option);
});

See Fiddle

Comments