Detect Content Type by Name JS
-
03-10-2020 - |
Question
I have some javascript running behind my NewForm.aspx. I would like to modify a Choice field based on the Content Type being used. I can determine the Content Type by checking the parameter:
GetUrlKeyValue('ContentTypeId')
But I'm assuming this GUID will change once I move to production. So instead of hard coding this check, is there a more reliable way to get the current Content Type through JavaScript? Say, by name and not GUID
Solution
You can use below JavaScript
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle("ListName");
var listContentTypes = oList.get_contentTypes();
clientContext.load(listContentTypes);
clientContext.executeQueryAsync(Function.createDelegate(this, onSuccess), Function.createDelegate(this, onFailed));
function onSuccess(sender, args) {
var e = listContentTypes.getEnumerator();
while (e.moveNext()) {
var ct = e.get_current();
if (ct.get_name() == "ContentTypeName") {
alert(ct.get_id());
break;
}
}
}
function onFailed() {
alert('Request Failed');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange