Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

html - Creating Dropdown Dynamically - Javascript

I'm trying to develop a JS function that creates a new row each time a new record is added to a database (from a different program that checks periodically). Right now I can get the function to check the db, add the record to the table and display it dynamically. The first column is the user id and the second column is where I'm running into issues. I would like to include a dropdown, but I'm not sure how to add options to it. I have the dropdown in the second column, but there are no options to choose from. Anyone have some suggestions?

function addRow(tableID, user) {

var table = document.getElementById(tableID);

var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var colCount = table.rows[0].cells.length;

for(var i=0; i<colCount; i++) {
    var opt = document.createElement("option");

     tabbody=document.getElementsByTagName("tbody").item(2);
     cell1 = document.createElement("TD");
     cell2 = document.createElement("TD");
     textnode1=document.createTextNode(user);
     //textnode2=document.createTextNode("morecontent");
     textnode2=document.createElement("select");
     textnode2.setAttribute('id', 'focus');
     textnode2.options.add(opt);
     cell1.appendChild(textnode1);
     cell2.appendChild(textnode2);
     row.appendChild(cell1);
     row.appendChild(cell2);
     tabbody.appendChild(row);

    var newcell = row.insertCell(i);

    newcell.innerHTML = table.rows[0].cells[i].innerHTML;

Here is the HTML that it is sent to:

        <th colspan="2">Pending Alerts</th>
    <tr>
       <th>User</th>
       <th>Action</th>
        </tr>
    <tbody>
    </tbody>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After

textnode2 = document.createElement("select");

you need to do something like

var op = new Option();
op.value = 1;
op.text = "First entry";
textnode2.options.add(op);      

and repeat for your desired entries.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...