Ok, after many hours of trying and failing, I found the solution thanks to a code snippet found in a discussion about adding a repeater row. 😅
First, you need to set a CSS class for the field you want to target. Enter it in the Presentation / Wrapper Attributes / class parameter input field.
Then, instead of the field key, we call the getField function with the DOM element:
var instance = new acf.Model({
events: {
'change .css_class_of_post_object_field': 'onChange',
'change .css_class_of_simple_text_field': 'onChange'
},
onChange: function(e, $el){
e.preventDefault();
var field = acf.getField( $el );
console.log( field.val() );
if ( !field.val() ) {
field.showError('This is a test error message!');
}
},
});
Why is this option not mentioned on the JavaScript API page? 🤔 Only filed_key is mentioned as a query parameter. 🤷♂️
Edit: Okay, I got it. I was inattentive because I only looked at the function parameter, not the description below. The 1-line description of the function does indeed state that the jQuery element is also a suitable reference.
I would still be interested in: is there a description of the showError function? I only saw it in an example code on the JavaScript API page, so I found out that this function exists.