tags:

views:

30

answers:

2

Hi,

Does anyone know how I could get the select options in the following to be populated from a SQL DB?:

        var cell2 = row.insertCell(1);
        var sel = document.createElement('select');
        sel.name = 'selRow' + rowCount;
        sel.options[0] = new Option('text zero', 'value0');
        sel.options[1] = new Option('text one', 'value1');
        cell2.appendChild(sel); 

Thanks, B.

A: 

Javascript can't directly connect to a database, you're going to need some server-side (PHP, ASP, Coldfusion, etc.) code to do that.

UPDATE: 1. In PHP create a page that reads the database & outputs XML or JSON or even the HTML code itself 2. In Javascript make an AJAX call to that PHP page 3. Use Javascript parse the XML/JSON/HTML response to update the page.

Using a library like JQuery will make this much easier to code. Let's assume your generating the HTML code in PHP & using JQuery, you could make & parse the AJAX call like this:

$.get("YourPHPPage.php", function(data){
   $('.DynamicSelect').html(data);
});

That will make an ajax call to the PHP page, and insert the result into your select box.

JKirchartz
i know, but am willing to incorporate PHP
Bift
OK, I've updated this with PHP/jQuery code....
JKirchartz
A: 

Either take the long and inelegant route of outputting each of the sel.options[x] lines when the page is generated, or if you want to do it based on other information on the form, using AJAX is the way.

gabe3886
how would you do it the inelegant way :-)
Bift
When generating the page at the server end, have a loop which will go through all of the results and output another option to the page.The loop would need to output sel.options[index] = new Option('text','value'); into the javascript
gabe3886