0

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,

2
  • If you are using happily jQuery to make development easy, why use Javascript in between? Commented May 25, 2015 at 17:09
  • 2
    var option = document.createElement("option"); should be in while loop Commented May 25, 2015 at 17:10

1 Answer 1

1

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++;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.