Skip to content

Instantly share code, notes, and snippets.

@fhdalikhan
Last active January 8, 2019 05:47
Show Gist options
  • Save fhdalikhan/6572c6f6dbf21c07f8baee76a2d548e9 to your computer and use it in GitHub Desktop.
Save fhdalikhan/6572c6f6dbf21c07f8baee76a2d548e9 to your computer and use it in GitHub Desktop.
Select2 populate option dynamically
var fromTitle = 'Paris';
var toTitle = 'paris_fr';
// Note: if id is same and title is updated then it won't change, so set a new id if you are updating a label and then set it back
var fromId = 'New York';
var toId = 'new-york-city_ny_us';
var newFromOption = new Option(fromTitle, fromId, false, false);
$('.fromLocation').eq(0).append(newFromOption); // add the option because of AJAX it would not exist
$('.fromLocation').eq(0).val(fromId); // Select the option with the value
$('.fromLocation').eq(0).trigger('change'); // Notify any JS components that the value changed
var newToOption = new Option(toTitle, toId, false, false);
$('.toLocation').eq(0).append(newToOption); // add the option because of AJAX it would not exist
$('.toLocation').eq(0).val([toId]); // Select the option with the value
$('.toLocation').eq(0).trigger('change'); // Notify any JS components that the value changed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment