eyst
eyst

Reputation: 1

Populating a <select> with data from ajax via javascript

although I found similar questions the solutions mentioned there wont seem to work for me.

What I'm trying to do:

  1. Fetch all the table names of my database with Ajax
  2. Fill the Table Names as options with respective values into a select field

How far I've come:

My fetch_devices php script echoes:

["test1","test2","test3"]

function FetchDevices(){
alert("Fetching");
$.ajax({
    url: 'php/sql/fetch_devices.php',
    success: function(devices) {
        var elements = Object.keys(devices).length;
        var select = document.getElementById("devices");
        var option = document.createElement("option");
        var i = 0;
        while(i < elements)
        {
            option.text= devices[i];
            option.value= devices[i];
            select.appendChild(option);
            i++;
        }

    },
    cache: false
});

}

But in the end I only see the last option "test3".....

Why is that happening?

Thanks in advance!

Best Regards,

Upvotes: 0

Views: 111

Answers (1)

Zee
Zee

Reputation: 8488

You are overriding the same option. Aslo make use of add(). Change it to

 while(i < elements)
    {
        var option = document.createElement("option");
        option.text= devices[i];
        option.value= devices[i];
        select.add(option);
        i++;
    }

Upvotes: 1

Related Questions