In this article, I am sharing code snippets to create List items and update items with Taxonomy or Managed Metadata field on a custom list. I have seen some threads on how to update the multi-value taxonomy fields also. The below code demonstrates both single/multi-valued, taxonomy column update snippets via JSOM.
Create List Item
- function CreateItem(isSingleValue){
- SP.SOD.executeOrDelayUntilScriptLoaded(function () {
- 'use strict';
- var context = new SP.ClientContext(_spPageContextInfo.siteAbsoluteUrl);
- var list = context.get_web().get_lists().getByTitle('CustomList');
- var itemCreateInfo = new SP.ListItemCreationInformation();
- var item = list.addItem(itemCreateInfo);
- var field = list.get_fields().getByInternalNameOrTitle("MyMMDField");
- var taxField = context.castTo(field, SP.Taxonomy.TaxonomyField);
- if(isSingleValue == true){ // this you have to handle manually , use
- var termValue = new SP.Taxonomy.TaxonomyFieldValue();
- termValue.set_label("MyWikiTerm");
- termValue.set_termGuid("fb58bc5e-5ce5-41fc-9a90-7431018aa935");
- termValue.set_wssId(-1);
- taxField.setFieldValueByValue(item, termValue);
- item.set_item("Title", "Created New Item and Set single valued Taxonomy");
- }
- else { // this you have to handle manually
- item.set_item("Title", "Created New Item and Multi valued Taxonomy");
- var pairs = "-1;#MyWikiTerm|fb58bc5e-5ce5-41fc-9a90-7431018aa935;#-1;#MyWikiTerm2|1cee8427-41f1-4a2b-aff3-26c67685988e";
- var termValueCollection = new SP.Taxonomy.TaxonomyFieldValueCollection(context,pairs,taxField);
- taxField.setFieldValueByValueCollection(item, termValueCollection);
- }
- item.update();
- context.load(item);
- context.executeQueryAsync(
- function () {
- console.log('Item created sucessfully: ' + item.get_id());
- },
- function (sender, args) {
- console.log("exception in addItem");
- });
- }, 'SP.Taxonomy.js');
- }
Go to page and view site in the Classic experience.
Press F12. Go to Developer Console and paste the above code in the console.
Press Enter.
We should get an undefined logged-in console. Don't worry. Ignore this message.






Ano MepaniPosted Jun 19, 2019, 4:37 AM
Does same functionality work with SPFX?