1) Call latest jQuery library
http://code.jquery.com/jquery-latest.min.js
2) JS Associate Array, data may come from ajax post
t={
'1': {id:1, name:'Andy'},
'2': {id:2, name:'Jiansen'},
'3': {id:3, name:'Tommy'}
};
3) Put t in dropdown menu and set default value 2
4) Able not to duplicate id
5) first we have a empty selection dropdown
<select id="mySelect"><option value=" ">=No TA Assigned=</option></select>
6) Then we have JS function myFunction() to deal with onclick to add items to dropdown, to append item in dropdown list
row.find('td.Ta select').append('<option value="'+taList[id0].id+'">'+taList[id0].name+'</option>');
7) We need to prevent duplication of items dropdown, also we can set the default value
row.find('td.Ta select').val('2');
Complete Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<style>
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
</style>
<script>
function myFunction() {
var taList = {};
taList={
'1': {id:1, name:'Andy'},
'2':{id:2,name:'Jiansen'},
'3': {id:3, name:'Tommy'} };
var row = $('table.template tr.template');
//add other options
for (var id0 in taList){
var x = document.getElementById("mySelect");
var i, add='y';
//prevent duplication
for (i = 0; i < x.length; i++) {
if(t[j].id ==x.options[i].value) add='y' ;
}
if(add=='y') row.find('td.Ta select').append('<option value="'+taList[id0].id+'">'+taList[id0].name+'</option>');
}
//Set default value, for example Andy
row.find('td.Ta select').val('2');
}
</script>
<body>
<h1>Add content in dropdown menu and set its default value in jQuery</h1>
<table class='template' style="border:1" >
<tr>
<th>Courses</th><th>Pick TA</th>
<tr>
<tr class='template'>
<td>Physics</td> <td class='Ta'><select id="mySelect"><option value=" ">=No TA Assigned=</option></select></td>
</tr>
</table>
<button onclick="myFunction()">Click me to add TAs TA dropdown list</button>
<p id="demo"></p>
</body>
</html>
Video: jQuery Modify dropdown menu and default value
Note: in video,
if(taList[id0].id ==i) add='n'
should be changed to
if(t[j].id ==x.options[i].value) add='y' ;