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>

No comments:

Post a Comment