Support

Account

Home Forums Front-end Issues Programmatically set the value of a select2 field.

Solved

Programmatically set the value of a select2 field.

  • Working with a front-end form, I want to programmatically set the value of a select2 taxonomy field after another field is updated.

    I have tried all manner of updating the value but it either doesn’t change or gets set to null. Any ideas? I thought I had a very simple task at hand, but its eluding me.

    This is what I have tried:

    
    const selectedValue = 12; //the id of the term I want to select
    $('#acf-field_5dcc4aa906709').val(selectedValue).trigger("change"); 
    
    var countyfield = acf.get_field('field_5dcc4aa906709');
    countyfield.val(selectedValue); 
    

    The first one should work according to the select2 documentation. This actually sets the value of the field to null.

    The second one I got from the ACF documentation. This updates the field object but does not update the field in the UI.

  • Ahah. Was just about to give up and found the solution on StackOverflow.

    Need to create the option and pass that to the field first, because ajax.
    new Option('label', 'value', true, true);

    Creates and sets the value. Huzzah!

    
     if ($("#acf-field_5dcc4aa906709").find("option[value=" + selectedValue + "]").length) {
       $('#acf-field_5dcc4aa906709').val([selectedValue]).trigger('change');
    } else {
       // Create the DOM option that is pre-selected by default
       var newCounty = new Option(county, selectedValue, true, true);
       // Append it to the select
       $("#acf-field_5dcc4aa906709").append(newCounty).trigger('change');
    }
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.