Home › Forums › General Issues › dependent dropdown select field › Reply To: dependent dropdown select field
I had to rework my code and use some of new 5.7 JavaScript APIs. For example they changed acf.prepare_for_ajax
to acf.prepareForAjax
. The way the data element is constructed also need changing as well as abandoning the acf.ajax.extend methodology.
Below is an attempt to rewrite your example using what I did as a basis. I make no guarantees that all my changes will make your example work, but they got my code back up and running. Hope it helps. I also left both the ready and change events in there in case people wanted to use e.type
to branch the code based on the event type.
jQuery(document).ready(function($){
if (typeof acf == 'undefined') { return; }
var acf_field = acf.getField('field_56e1cf2e7ad26');
acf_field.on("change ready", function(e){
// bail early if no ajax
if( !acf.get('ajax') ) return;
// abort XHR if it's already running
if( this.request ) {
this.request.abort();
}
// set the ajax action that's set up in php
var data = {
action: 'get_sub_terms',
key_name: acf_field.val(); //The key_name needs to be the name of the parameter in your action
}
this.request = $.ajax({
url: acf.get('ajaxurl'), // ajax url, acf already sets this
data: acf.prepareForAjax(data), // another included acf function
type: 'post', // posted values, look at $_POST in your php ajax action function
dataType: 'json', // how we want the date returned
success: function( json ){
// get the field we want to populate
var $select = $('.acf-field-56e2b71dde0c5 select');
// this stores the currenlty selected value in that field
// so that we can mark it as selected, this is important when loading
// and exsiting post
var $selected = $select.val();
// clear all of the exsiting options from the field
$select.empty();
// rebuild the child select field
$select.append('<option data-i="" selected="selected" value="">- Select -</option>');
var count = json.length;
for (i=0; i<count; i++) {
var $item = '<option value="'+json[i]['value']+'"'
if ($selected == json[i]['value']) {
$item += ' selected="selected"';
}
$item += '>'+json[i]['label']+'</option>';
$select.append($item);
}
}
}); // end ajax
});
// trigger the ready action to load the field
// this is important for existing posts
$('#acf-field_56e1cf2e7ad26').trigger('ready');
});
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.