
Dynamic dropdown options always use in our Application. It can be based on user first selection to return a new listing to second dropdown options by AJAX.
Below is the example PHP array script:
$option = array();
$option[] = array('name' => 'fruits', 'value' => 'f');
$option[] = array('name' => 'vegetables', 'value' => 'v');
$option[] = array('name' => 'pizza', 'value' => 'p');
And now we need the Jquery script to build the dropdown select. Below script are allow to reuse again when you need to replace the dropdown option again.
(function($, window) {
$.fn.populateOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.value)
.text(option.name);
self.append($option);
});
};
})(jQuery, window);
How to use it.
<select id="dropdown" name="dropdown"></select>
<script>
var options = <?php echo json_encode($option); ?>
$("#dropdown").replaceOptions(options);
</script>
Below is the completed DEMO to show how it work:
Jquery simple dynamic dropdown options with PHP array