Reputation: 1873
I need to populate a dropdown list when I select a certain value and the options need to be queried from the database.
Can I achieve this from jQuery ? If I can then please I would appreciate any help..
Upvotes: 3
Views: 2695
Reputation: 94147
You can definitely achieve this. You need to use AJAX.
Ajax is a subject all in itself, but basically what you will do is call a javascript function when a selection is made from the dropdown. The javascript function will request a page from your server via Ajax, and the server will return a small chunk of data, which you can then use (from Javascript again) to re-populate the second drop down (or whatever).
Google around for how to do Ajax with Jquery. Here's a page that might get you started: http://www.ajaxlines.com/ajax/stuff/article/use_jquery_ajax_to_create_options_in_a_dropdown_menu.php
Upvotes: 0
Reputation: 301
Note that appending each <option>
to the <select>
will reload the DOM for each append. This can become very slow if you have a lot of options.
It is more efficient to build the whole <select>
with its option in a string and then replace the existing one.
Upvotes: 0
Reputation: 254
You can do it with jQuery and AJAX
jQuery.post('dropdownValues.php', {parameterSentToServer1:'value', param2:'value2'}, function(data){jQuery('#mydropdown option').remove(); //Remove current options
for (var option in data.results){
jQuery('#mydropdown').append('<option value="'+option.value+'">'+option.name+'</option>');
}}, 'json');
in dropdownValues.php you'll need to build a json object with the result of the sql query, the object must be in this format(for working well with the above script):
echo '{results:[{value:1, name:'Option1'}, {value:2, name:'Option2'}]};
Upvotes: 2
Reputation: 125470
Does "drop down list" refer to a popup menu (e.g. a <select>
element)? If so, you can populate it as follows:
var data = ["Hello World!", 42, true, "Foo"];
var select = document.getElementById("myPopupMenu");
for (var i = 0, l = data.length; i < l; i++)
{
var option = new Option();
option.innerHTML = data[i];
select.appendChild(option);
}
However, this is in plain JavaScript—I'm not sure what the jQuery syntax would be.
Steve
Upvotes: 0