Skip to content
Amal Hashim
All posts
Snippet

SharePoint 2013 - Get Term ID from Name using JSOM

A JSOM function that looks up a managed metadata term by name in a term set and writes name|id into a hidden field.

1 min read#JavaScript#SharePoint#SharePoint 2013

This function fetches a term ID from the term name. It searches one term set in the default keywords term store and writes name|id into an input element. If the input already has a value, the new pair is appended after a semicolon.

js
function GetFullTermStringByName(termName, termSetId, inputId) {
    var clientContext = new SP.ClientContext.get_current();
    var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
    var termStore = taxSession.getDefaultKeywordsTermStore();
    var termSet = termStore.getTermSet(termSetId);
    var terms = termSet.getAllTerms();
    clientContext.load(terms);
    clientContext.executeQueryAsync(
        function () {
            var e = terms.getEnumerator();
            while (e.moveNext()) {
                var term = e.get_current();
                if (term.get_name() == termName) {
                    var element = document.getElementById(inputId);
                    if (element.value == '')
                        element.value = termName + '|' + term.get_id();
                    else
                        element.value = element.value + ';' + termName + '|' + term.get_id();
                    break;
                }
            }
        },
        onFail
    );
}

function onFail() {
    // FAILED
}

GetFullTermStringByName('Sales', 'xyzabcde-c68d-4c6d-b587-48ddaf1aecc9', 'HIDDEN_ELEMENT_ID');

Example

If the term set contains a term called "Sales" with ID 1a2b..., the hidden input ends up with Sales|1a2b.... Calling the function again for another term gives Sales|1a2b...;Marketing|3c4d....