views:

683

answers:

5

hi i need to populate a drop down 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..

A: 

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

Steve Harrison
there is no problem in getting the value but , how can i populate the drop down list ?
jarus
Right, I see. I've updated my answer to address your question.
Steve Harrison
A: 

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

zombat
A: 

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'}]};
xaguilars
A: 

You can do it with this plugin troubleless. http://www.texotela.co.uk/code/jquery/select/

A: 

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.

w00kie