Skip to content Skip to sidebar Skip to footer

Populate Dropdown Dynamically Using Json Data

I am having problems displaying the names of golf courses in my dropdown menu. I have a PHP script that when ran, returns the names of the courses in my database. The problem is th

Solution 1:

You need to put text in options as below :

var dummyData = ['English','Spanish','French','Mandarin'];

$(document).ready(function () {
    var data = dummyData, //This data comes from the ajax callback
        courseOptions = "";

    for(var i=0; i< data.length; i++){
       courseOptions += '<option value ="' + data[i] + '">'+data[i]+'</option>';
    }

   $("#selectCourse").append(courseOptions);

});

Working Demo : jsFiddle

Solution 2:

Currently you are not setting text of option also, use

options += '<option value ="' + data[i] + '">' +  data[i]  + '</option>'

instead of

options += '<option value ="' + data[i] + '">' + '</option>';

Solution 3:

As you're currently utilizing jQuery, you may want to go for this solution:

for(var i=0; i< data.length; i++)
{
    $("#selectCourse").append(
        $('<option>').text(data[i]).val(data[i])
    );
}

Solution 4:

Use .html(options); in place of .append(options); .

append() add data after tag but html() insert data between tag.

and you should also assign something between tag, like

options += '<option value ="' + data[i] + '">' +  data[i]  + '</option>'

Solution 5:

First log your data like console.log(data) and check in browser firebug console whether it outputs json string or object. If it's string you need to convert it into object using JSON.parse().

Post a Comment for "Populate Dropdown Dynamically Using Json Data"