In this blog I would like to share the code to add the custom fields on SharePoint host web list using SharePoint hosted app.
In *.aspx page add HTML Button
<button type="button" id="btnCreate">Add Field</button>
Write below code on *.js file,
  1. //get Current Context
  2. var context = SP.ClientContext.get_current();
  3. // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
  4. $(document).ready(function () {
  5. console.log("page loading...");
  6. $("#btnCreate").click(function () {
  7. addField();
  8. });
  9. });
  10. //this method is used to add the fields on custom list
  11. function addField() {
  12. //Get host web URL
  13. var hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
  14. //get app context using host web url
  15. var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
  16. //get current web
  17. var currentWEB = appCtxSite.get_web();
  18. //get list from host web
  19. var list = currentWEB.get_lists();
  20. //load the list
  21. context.load(list);
  22. context.executeQueryAsync(function () {
  23. //get custom list by name
  24. var currentList = list.getByTitle("sampleList");
  25. //get field collection from current list
  26. var fldCollection = currentList.get_fields();
  27. //set the type and field details
  28. var f1 = context.castTo(fldCollection.addFieldAsXml('<Field Type="Text" DisplayName="Person Name" Name="PersonName" />', true, SP.AddFieldOptions.addToDefaultContentType), SP.FieldText);
  29. f1.set_title("PersonName");
  30. //update
  31. f1.update();
  32. context.executeQueryAsync(function () {
  33. console.log("Field Creation Success");
  34. },
  35. function (sender, args) {
  36. console.log("Field Creation failed : " + args.get_message());
  37. });
  38. }, function (sender, args) {
  39. onfail(sender, args);
  40. });
  41. }
  42. // This function is executed if the above call fails
  43. function onfail(sender, args) {
  44. alert('Failed to add field in list. Error:' + args.get_message());
  45. }
  46. // this method used split the query string
  47. function manageQueryStringParameter(paramToRetrieve) {
  48. var params = document.URL.split("?")[1].split("&");
  49. var strParams = "";
  50. for (var i = 0; i < params.length; i = i + 1) {
  51. var singleParam = params[i].split("=");
  52. if (singleParam[0] == paramToRetrieve) {
  53. return singleParam[1];
  54. }
  55. }
  56. }
Note - In app manifest file provide full control permission to the web as shown in below,
Summary
In this blog we have explored how to add the custom fields in host web list using SharePoint hosted app with JavaScript Object model. Happy coding !!