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' ;
Hello
ReplyDeleteWe are professional traders, earning on forex and binary for investors weekly, will love to tell you all more about our investment platform where you can invest funds as little as $200 and start earning $2500 weekly, alot of people has benefited from this investment offer before and during this convid-19 virus, if you passing through financial difficulties due to this coronavirus and you need help paying bills simply choose a suitable investment plan for yourself and start making profit weekly
$500 to earn $5,000 in 7 days
$1000 to earn $10000 in 7 days
$5000 to earn $50000 in 7 days
To Start your investment now contact Via whatsapp: (+12166263236)
email: carlose78910@gmail.com