We have 2 drop down boxes.
When we select one, we want that second one to be auto-populated with corresponding values to our selection.
This snippet is part of a php code invoked by ajax. It’s purpose is to respond to ajax call in form {“values”:[{“value”:”txt”},{…}]}
Ex: {"values":[{"value":"10","txt":"Aged care service"},{"value":"11","txt":"Social housing"}]}
1 2 3 4 5 6 7 8 |
$response = '{"values":['; foreach($ret_array as $key=>$value) { $response .= '{"value":"' . $value['value_tx'] .'","txt":"' . $value['long_val_tx'] . '"},'; } $response = substr_replace($response ,"",-1); $response .= ']}'; echo $response; |
Ajax call:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function populateEntityTypes() { var categorySelect = jQuery('#category_cd').val(); //this is our select combobox var entityTypeDropdown = jQuery('#serv_class_cd'); //this is the dropdown to be populated dynamically jQuery.ajax( { type:"POST", url:"ajax/getEntityTypes.php", data:"categorySelectId=" + categorySelect, //we send categoryId to execute a sql findById success:function (data) { entityTypeDropdown.empty(); //delete previous options in dropdown var myObject = jQuery.parseJSON(data); //convert json to object jQuery.each(myObject.values, function(index, obj) { //parse the 'values' var option = jQuery('<option></option>'); //prepare options in dropdown option.attr('value', obj.value).text(obj.txt); //inject values entityTypeDropdown.append(option); //add our values }); } } ); } |
Trigger can be:
1 2 3 4 5 6 |
jQuery(document).ready(function ($) { jQuery('#category_cd').change(function(event){ populateEntityTypes(); }); }); |
or using “onChange” event in combobox.