Reputation: 1174
I'm new to createElement
property in JavaScript. I need to create a dropdown menu from the MySQL query. I have created a PHP array from the MySQL query, which is given below:
<?
$vendorInformation=mysql_query("SELECT * FROM `vendor`",$con);
$row=array();
while($v=mysql_fetch_assoc($vendorInformation))
{
$row[]= $v['id'];
$row[]= $v['name'];
}
$row=json_encode($row);
echo $row;
//OUTPUT: ["1","Cisco","2","Juniper","3","Opengear"]
?>
Then I wrote the JavaScript code:
<script>
var inputs = 1;
var v_array = <?=$row;?>;
//OUTPUT for v_array: 1,Cisco,2,Juniper,3,Opengear
var inp3 = document.createElement('SELECT');
var o=document.createElement("option");
inp3.setAttribute("id","v"+(inputs));
for (var i = 0; i < v_array.length; i++)
{
var o=document.createElement("option");
o.setAttribute("name","red");
o.setAttribute("value","me");
o.innerHTML=name;
inp3.appendChild(o);
}
</script>
I'm not sure how can I complete this code.
As per the array's output, the option value should be 1,2,3 and values should be Cisco,Juniper,Opengear(respectively).
Upvotes: 1
Views: 495
Reputation: 324750
You would be better off using this format in your PHP:
while($v = mysql_fetch_assoc($vendorInformation)) {
$row[] = array(
"id"=>$v['id'],
"name"=>$v['name']
);
}
Then, in your JavaScript, you can do this:
var inp3 = document.createElement('select'),
l = v_array.length, i;
for( i=0; i<l; i++) {
inp3.options[i] = new Option(v_array[i].name,v_array[i].id);
}
Upvotes: 1