Adsense
Popular Posts
- Code update from PHP 7.4 to PHP 8.1 - PhpSpreadsheet
- MySQL workbench -"Could not decrypt password cache"
- Code update from PHP 7.4 to PHP 8.1 - Worksheet/Iterator.php
- Rendering HTML tags inside textarea
- axios handle blob type data
- Unix Utils and wget in Windows
- increase mysql query speed
- Setup vi syntax for PHP
- Get WAMP running on EC2
- add comment to table columns in phpMyAdmin
Thursday, October 23, 2014
Add content in dropdown menu dynamically and set its default value in jQuery
To add content in dropdown menu and set its default value in jQuery,
1) first we have a empty selection dropdown
<select id="mySelect"><option value=" ">=No TA Assigned=</option></select>
2) Then we have JS function myFunction() to deal with onclick to add items to dropdown, this is very useful as we can change dropdown menu dynamically.
3) 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(taList[id0].id ==i) add='n'
}
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>
Labels:
jQuery
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment