This code provides an interactive UI for adding columns to a SharePoint list. Users can dynamically add or remove column rows and select the column type (e.g., Text, Choice, DateTime) using a user-friendly form built with HTML, CSS, and jQuery.
Key Features
- Dynamic Column Addition: The addColumnRow() function allows users to add new columns using a "+" button. Each row includes options for column name and type.
- Column Types: Supports various column types, including text, choice, and number fields. For choice columns, users can input options separated by semicolons.
- SharePoint Integration: The script uses the SharePoint JavaScript Object Model (JSOM) to retrieve lists and create columns on the selected list.
- Default View: Users can choose to add new columns to the default view using a checkbox.
How to Use SharePoint Column Creator?
- Add Columns: Click the "+" button to add a new column row. Enter the column name and select the type. For Choice columns, enter options separated by semicolons.
- Select List: Choose a SharePoint list from the dropdown.
- Create Columns: Click "Create Columns" to add the columns to the list.
Script Execution
The createColumnsBtn click event collects column information and builds the XML required to create fields in SharePoint. The getFieldType() function maps the selected column type to SharePoint’s field types. The script uses SP.ClientContext to add fields to the list.
The Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SharePoint Column Creator</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
color: #333;
margin: 20px;
}
.container {
max-width: 600px;
margin: auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #0078d4;
}
label {
font-weight: bold;
margin-bottom: 8px;
display: inline-block;
}
select, input[type="text"] {
width: 100%;
padding: 10px;
margin-bottom: 12px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
#columnsContainer .columnRow {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.columnRow button {
background-color: #0078d4;
color: white;
border: none;
border-radius: 50%;
width: 28px;
height: 28px;
font-size: 16px;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
margin-right: 10px;
margin-left: 5px;
}
.columnRow button.removeRowBtn {
background-color: #d9534f;
margin-left: 10px;
}
.choicesInput {
margin-top: 8px;
width: calc(100% - 38px);
margin-left: 38px;
}
.buttonContainer {
text-align: center;
margin-top: 20px;
}
.buttonContainer button {
background-color: #0078d4;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
border-radius: 4px;
cursor: pointer;
}
.buttonContainer button:hover {
background-color: #005a9e;
}
.checkboxContainer {
display: flex;
align-items: center;
margin-top: 12px;
}
.checkboxContainer input[type="checkbox"] {
margin-right: 10px;
}
</style>
</head>
<body>
<div class="container">
<h2>Create SharePoint Columns</h2>
<label for="listDropdown">Select List:</label>
<select id="listDropdown"></select>
<div id="columnsContainer"></div>
<div class="checkboxContainer">
<input type="checkbox" id="defaultViewCheckbox">
<label for="defaultViewCheckbox">Add to default view</label>
</div>
<div class="buttonContainer">
<button id="createColumnsBtn">Create Columns</button>
</div>
</div>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var columnCount = 0;
function addColumnRow() {
columnCount++;
var newRow = `
<div class="columnRow" id="columnRow_${columnCount}">
<button type="button" class="addRowBtn">+</button>
<input type="text" id="columnName_${columnCount}" placeholder="Column Name" />
<select id="columnType_${columnCount}" class="columnType">
<option value="Text">Single line of text</option>
<option value="Note">Multiple lines of text</option>
<option value="Choice">Choice</option>
<option value="MultiChoice">Multiple Choice (Checkboxes)</option>
<option value="Number">Number</option>
<option value="DateTime">Date and Time</option>
<option value="Boolean">Yes/No</option>
<option value="User">Person or Group</option>
</select>
<button type="button" class="removeRowBtn">-</button>
<div id="choicesContainer_${columnCount}" class="choicesContainer" style="display:none;">
<input type="text" class="choicesInput" placeholder="Enter choices separated by ;" />
</div>
</div>`;
$('#columnsContainer').append(newRow);
}
// Initial row
addColumnRow();
// Event delegation for dynamic elements
$('#columnsContainer').on('click', '.addRowBtn', function (e) {
e.preventDefault();
addColumnRow();
});
$('#columnsContainer').on('click', '.removeRowBtn', function (e) {
e.preventDefault();
$(this).closest('.columnRow').remove();
});
$('#columnsContainer').on('change', '.columnType', function (e) {
var selectedType = $(this).val();
var choicesContainer = $(this).siblings(`#choicesContainer_${$(this).attr('id').split('_')[1]}`);
if (selectedType === 'Choice' || selectedType === 'MultiChoice') {
choicesContainer.show();
} else {
choicesContainer.hide();
}
});
$('#createColumnsBtn').click(function (e) {
e.preventDefault();
var listName = $('#listDropdown').val();
var addToDefaultView = $('#defaultViewCheckbox').is(':checked');
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listName);
var fieldCreationInfo = [];
$('#columnsContainer').children('.columnRow').each(function () {
var columnName = $(this).find('input[id^="columnName"]').val();
var columnType = $(this).find('select[id^="columnType"]').val();
var choices = $(this).find('.choicesInput').val();
if (columnName) {
fieldCreationInfo.push({
'name': columnName,
'type': columnType,
'choices': choices
});
}
});
fieldCreationInfo.forEach(function (field) {
var fieldXml = `<Field DisplayName='${field.name}' Name='${field.name}' Type='${getFieldType(field.type)}'>`;
if (field.type === 'Choice' || field.type === 'MultiChoice') {
var choicesXml = "<CHOICES>";
var choicesArray = field.choices.split(';');
choicesArray.forEach(function (choice) {
choicesXml += `<CHOICE>${choice.trim()}</CHOICE>`;
});
choicesXml += "</CHOICES>";
fieldXml += choicesXml;
}
fieldXml += "</Field>";
var field = list.get_fields().addFieldAsXml(fieldXml, addToDefaultView, SP.AddFieldOptions.defaultValue);
ctx.load(field);
});
ctx.executeQueryAsync(
function () {
alert("Columns created successfully!");
},
function (sender, args) {
alert("Failed to create columns. " + args.get_message());
}
);
});
function getFieldType(type) {
switch (type) {
case 'Text': return 'Text';
case 'Note': return 'Note';
case 'Choice': return 'Choice';
case 'MultiChoice': return 'MultiChoice';
case 'Number': return 'Number';
case 'DateTime': return 'DateTime';
case 'Boolean': return 'Boolean';
case 'User': return 'User';
default: return 'Text';
}
}
function loadLists() {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var lists = web.get_lists();
ctx.load(lists, 'Include(Title)');
ctx.executeQueryAsync(function () {
$('#listDropdown').empty();
$('#listDropdown').append('<option value="">Select a List</option>');
var listEnumerator = lists.getEnumerator();
while (listEnumerator.moveNext()) {
var list = listEnumerator.get_current();
$('#listDropdown').append(`<option value='${list.get_title()}'>${list.get_title()}</option>`);
}
}, function (sender, args) {
alert("Failed to load lists. " + args.get_message());
});
}
// Ensure the dropdown is populated after the page loads
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', loadLists);
});
</script>
</body>
</html>
Final Step
Integrate this script into a SharePoint page using a Script Editor web part. Ensure you have the necessary permissions to modify the list schema. This tool is ideal for administrators looking to streamline column management in SharePoint lists.
How will it look like?
From the Select List dropdown, you can select the list you want to create columns, in column names, you can put the name of the column you want to create, and the box beside it lets you select the type of the column. The "+" and "-" signs are for adding one more row to create another column so that you can create and add multiple columns in one go. Also, you can choose to add that column in the default view, after everything you can click on "Create Columns" to create the columns.
After the successful creation of the column, you'll see the alert "Columns Created Successfully."