dougfitz

ACF field population jQuery

Aug 27th, 2019
151
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. jQuery(document).ready(function($) {
  2.  
  3. var acffield_committee = '#acf-field_5c646d5e7f431';
  4. var acffield_location = '#acf-field_5c64709d7f436';
  5.  
  6. // Add default 'Select one'
  7. $( acffield_committee ).prepend( $('<option></option>').val('0').html('Select Committee').attr({ selected: 'selected', disabled: 'disabled'}) );
  8.  
  9. /**
  10. * Get committee options on select menu change
  11. *
  12. */
  13. $( acffield_committee ).change(function () {
  14.  
  15. var selected_committee = ''; // Selected value
  16.  
  17. var my_selected_committee = pl_vars.selected_committee;
  18. var my_selected_location = pl_vars.selected_location;
  19.  
  20. // Get selected value
  21. $( '#acf-field_5c646d5e7f431 option:selected' ).each(function() {
  22. selected_committee += $( this ).text();
  23. });
  24.  
  25. $( acffield_location ).attr( 'disabled', 'disabled' );
  26.  
  27. // If default is not selected get default location for selected committee
  28. if( selected_committee != 'Select Committee' ) {
  29. // Send AJAX request
  30. data = {
  31. action: 'pl_add_location',
  32. pl_nonce: pl_vars.pl_nonce,
  33. committee: selected_committee,
  34. };
  35.  
  36. // Get response and populate location field
  37. $.post( ajaxurl, data, function(response) {
  38.  
  39. if( response ){
  40. // Disable Location field until country is selected
  41. //$( acffield_location ).html( $('<option></option>').val('0').html('Select Area').attr({ selected: 'selected', disabled: 'disabled'}) );
  42. $( acffield_location ).attr({ selected: 'selected', disabled: 'disabled'});
  43.  
  44. // Add areas to select field options
  45. $.each(response, function(val, text) {
  46. $( acffield_location ).val(text);
  47. });
  48.  
  49.  
  50.  
  51. // No idea where this goes. Need to save selected_committee choice as well as value for location (whether it's prepopulated or something new typed in by user.)
  52.  
  53. $('.my-select option[value="' + my_selected_location +'"]').attr('selected', 'selected');
  54.  
  55.  
  56.  
  57.  
  58.  
  59. // Enable 'Select Location' field
  60. $( acffield_location ).removeAttr( 'disabled' );
  61. };
  62. });
  63. }
  64. }).change();
  65. });
RAW Paste Data