Skip to content

Instantly share code, notes, and snippets.

@oguzhankircali
Last active May 15, 2019 13:18
Show Gist options
  • Save oguzhankircali/b90a433a6f356d95c515bd2121cb34dd to your computer and use it in GitHub Desktop.
Save oguzhankircali/b90a433a6f356d95c515bd2121cb34dd to your computer and use it in GitHub Desktop.
<select id="ddlModules" class="select2"></select>
populateSelect2("ddlModules", null, "");
function populateSelect2(elemId, data, selectedValue) {
var $select = $("#" + elemId);
$.each(data, function (ix, obj) {
var itemSelected = false;
if (isObjValid(selectedValue)) {
itemSelected = (selectedValue === obj.id);
}
var newOption = new Option(obj.text, obj.id, false, itemSelected);
$select.append(newOption);
});
if (!isObjValid(selectedValue) && !isInputRequired($select)) {
$select.val(null);
}
$select.trigger("change");
}
function isObjValid(obj) {
if (typeof (obj) === "undefined" || obj === null) { return false; }
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment