Search code examples
javascriptcfmlcfquerycoldfusion-7

How to populate a dynamically created dropdown box in a using javascript and coldfusion


I have a dropdown box in a row that was dynamically created. I'm populating that box on within the screen. Is there a way that I can use cfquery to get the info from the sql server and populate the dropdown box. I would like to do it within the javascript?

Here is my code:

<script language="javascript" type="text/javascript">
function addRow() {

    var tbl = document.getElementById('tblSample');
    var lastRow = tbl.rows.length;  
    var iteration = lastRow;
    var row = tbl.insertRow(lastRow);

  // left cell
    var cellLeft = row.insertCell(0);
    var textNode = document.createTextNode(iteration-3);
    cellLeft.appendChild(textNode);

      // select cell
    var cellRightSel = row.insertCell(1);
    var sel = document.createElement('select');
    sel.name = 'sectCode' + iteration;
    sel.id = 'sectCode' + iteration;    
    sel.options[0] = new Option('---Any---', '0');
    sel.options[1] = new Option('Level 0.5: test1, '1');
    sel.options[2] = new Option('Level I: test2', '2');
    sel.options[3] = new Option('Level I.D: test3', '3');
    sel.options[4] = new Option('Level II.1: test4', '4');
    sel.options[5] = new Option('Level II.5: test5', '5');
    cellRightSel.appendChild(sel);

}

Solution

  • plalx's answer is good, but if you really want to do it in Javascript, you can simply do something like this:

    sel.options[0] = new Option('---Any---', '0');
    <cfoutput query="yourQuery">
        sel.options[#yourQuery.CurrentRow#] = new Option('#yourQuery.value#', '#yourQuery.text#');
    </cfoutput>
    

    You may also want to use ColdFusion's JSStringFormat function to prevent things like apostrophes within those values from the query causing any problems in your Javascript:

    sel.options[0] = new Option('---Any---', '0');
    <cfoutput query="yourQuery">
        sel.options[#yourQuery.CurrentRow#] = new Option('#JSStringFormat(yourQuery.value)#', '#JSStringFormat(yourQuery.text)#');
    </cfoutput>