Support

Account

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

  • 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');
    }