Support

Account

Home Forums Backend Issues (wp-admin) Getting select value on change with jQuery

Helping

Getting select value on change with jQuery

  • Hi everyone,

    So I’ve got a taxonomy field that is displayed as a dropdown select. Using jQuery I would like to get the value of that select when it is clicked on. Normally I would use something like:

    $( "#taxonomySelect" ).change(function () {
        alert(this.value);
    });

    But it doesn’t work because ACF doesn’t generate a regular select input. When clicked, the dropdown populates a span with a ul and lis with the options. And no matter what I try, I can’t get jQuery to pick up the value of the selected li…

  • It can be complicated, the first thing that you need to be able to do is to detect that a field has changed. This might require targeting a hidden field depending on the field type. Once you do that, in order to get the value of the field you need to use the ACF JS API https://www.advancedcustomfields.com/resources/javascript-api/

    The following has not been tested, it is just an example and some testing/debugging may need to be done

    
    (function($){
      if (typeof acf === 'undefined') {
        return;
      }
      
      // detect change of tax field ??
      // insert the field key of your tax field
      // need to use $(document).on because field may be dynamically inserted and may not exist when the document is ready
      // this might need to target the hidden field, not sure, testing would be required
      // it really depends on the specifics of the field settings
      // you need to inspect the HTML see the structure of the field
      $(document).on('change', '[data-key="field_XXXXXXXXX"] .acf-input select', function(e) {
        
        // once your getting the change event to fire
        // get field value using ACF JS API
        var field = acf.getField('field_XXXXXXXXX');
        var value = field.val();
        
      });
    })(jQuery);
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Getting select value on change with jQuery’ is closed to new replies.