Support

Account

Home Forums General Issues Update acf field using javascript API

Solving

Update acf field using javascript API

  • Hi everyone,

    I know this is probably an amazingly silly question, but can someone guide me on how to update a custom field’s value using the javascript API? I know that this can be done with PHP and AJAX, but (probably unsurprisingly given I’m even asking this question) that’s beyond my capability at the moment.

    I’ve looked into the acf.set and field.val functions/actions, and none seem to be done it. I think this is because they’re just loading data into the javascript and not actually updating the field, so I’m hoping someone can help me identify how to do that.

    Thanks in advance!

  • I’m working on a situation where I’m doing this now. Basically, I am updating fields based on other selections. This does not update the field in the database, it only updates the field on the page that you are currently editing and you must still save the page.

    A basic example, let’s say that there is a text field we want to update based on a choice in a select field. First you need to add a custom JS file, see this https://www.advancedcustomfields.com/resources/adding-custom-javascript-fields/

    
    jQuery(document).ready(function($) {
      // everything is in this JQ wrapper that runs when the page is loaded
      
      // first, make sure that acf exists, if it doesn't then return
      if (typeof(acf) == 'undefined') { return; }
      
      // get the acf select field and add a change event to it
      // you need to supply the field key of your field
      var field = acf.getField('field_12345');
      // add a change event to the field
      field.on('change', function(e) 
        // get the other field we want to change
        var other_field = acf.getField('field_654321');
        if (e.$el.val() == 'some value') {
          // if the value of the field that was changes matches some criteria 
          // change the value of the other field
          other_field.val('new value for other field');
        }
      });
    });
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Update acf field using javascript API’ is closed to new replies.