开发者

Dynamic Dropdown List from SQL with JS

Please help, I have a dynamic JS table, so you can add and delete rows by clicking a button. One field that I need to add within the row is a select box, no problem so for and I use the following:

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);

So the above creates a select box, named based on the row ID using rowCount. Where I’m stuck is I need to dynamically开发者_StackOverflow中文版 populate the options, I can do this with php using the following, but it is linking the JS and PHP that I’m stuck on:

$getProd_sql = 'SELECT * FROM products';
$getProd = mysql_query($getProd_sql);                 
$prov = "<select name=\"product\" id=\"product\" onChange=\"testajaxprod();\">";
$prov .= " <option value=\"0\" selected=\"selected\">Select Product</option>";
        while($row = mysql_fetch_array($getProd))
        {
            $prov .= "<option value=\"$row[product_id]\">$row[product_name]</option>";
        }
$prov .= "</select>";

Your help is very much appreciated.

Thanks, B.


You can add PHP in the middle of your JS. PHP will run first and leave you with a file containing the values as if my magic.

To populate from PHP instead of producing your data in text you can do this.

$getProd_sql = 'SELECT * FROM products';
$getProd = mysql_query($getProd_sql);   
while($prod = mysql_fetch_object($getProd))
{
  ?>
     var text = documentElement.createElement('select');
     documentElement.value = <?=$prod->value?>
  <?
}

Notice the way you can break in and out of PHP with . Also saves you from writing "echo" or anything. You will have to replace the simple text box with your dropdowns or whatever.

Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜