In this article, you can find examples of how to use JavaScript to make your forms more interactive by hiding, disabling, and making fields mandatory based on certain conditions. Learn how to work with specific field types via JavaScript in SharePoint fields section.
In order to access fields in JavaScript, you’ll need to use the fd.field() method, which expects a name of a field you want to retrieve. The name of each field on the form is unique. Select a field and copy its name from the Name property:
Note
You should place JavaScript inside fd events like spRendered() or spBeforeSave() to access the fields or controls that you target.
If you just add these scripts on their own or inside the wrong event in the JavaScript editor, they will not have access to the specified fields, or will execute at the wrong time. Read more about different events in the JavaScript framework basics article.
Set the field once the form loads:
fd.spRendered(function(vue) {
fd.field('StartDate').value = new Date();
});
For some fields, such as Lookup or Person, you might need to wait until the field is ready, before you can assign a value:
fd.spRendered(() => {
fd.field('Lookup').ready(function(field) {
//set Lookup field value once the field loads
field.value = 5;
});
});
You can also populate field values from URL parameters, for example:
//https://domain.sharepoint.com/sites/sitename/SitePages/PlumsailForms/ListName/Item/NewForm.aspx?param1=abc¶m2=xyz
fd.spRendered(() => {
var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
fd.field('Text1').value = urlParams.get('param1');
fd.field('Text2').value = urlParams.get('param2');
});
Set the field’s hint once the form loads:
fd.spRendered(() => {
fd.field('Name').placeholder = 'Enter your full name';
});
Set the field’s title once the form loads:
fd.spRendered(() => {
fd.field('Name').title = 'Full Name';
});
Set the field once value of another field changes:
fd.spRendered(() => {
function setPercentComplete() {
if (fd.field('Status').value == 'Completed') {
// Setting the Percent Complete to 100
fd.field('PercentComplete').value = '100';
}
}
// Calling setPercentComplete when Status value changes
fd.field('Status').$on('change',setPercentComplete);
// Calling setPercentComplete on form loading
setPercentComplete();
});
Disable field once specific conditions are meant.
fd.spRendered(() => {
function disablePercent() {
if (fd.field('Status').value == 'Completed' && fd.field('PercentComplete').value == '100') {
// Setting field PercentComplete to a disabled state
fd.field('PercentComplete').disabled = true;
}
else{
// Setting field PercentComplete to an editable state
fd.field('PercentComplete').disabled = false;
}
}
// Calling disablePercent when the PercentComplete value changes
fd.field('PercentComplete').$on('change',disablePercent);
// Calling disablePercent on form loading
disablePercent();
});
Hide/show fields once value of another field changes:
fd.spRendered(() => {
function hideOrShowDueDate() {
if (fd.field('StartDate').value) {
// Show the Due Date field
fd.field('DueDate').hidden = false;
} else {
// Hide the Due Date field
fd.field('DueDate').hidden = true;
}
}
// Calling hideOrShowDueDate when the Start Date value changes
fd.field('StartDate').$on('change',hideOrShowDueDate);
// Calling hideOrShowDueDate on form loading
hideOrShowDueDate();
});
Clear fields once value of another field changes:
fd.spRendered(() => {
function clearFields() {
if (fd.field('Status').value == 'Not started') {
// Clear fields of any value
fd.field('StartDate').clear();
fd.field('DueDate').clear();
}
}
// Calling clearFields when the Status value changes
fd.field('Status').$on('change',clearFields);
});
You can add custom validators to a field to ensure that the value meets certain criteria, and trigger validation when the value of the field changes:
fd.spRendered(() => {
fd.field('Attachments').addValidator({
name: 'Attachments validator',
error: 'Do not attach more than 3 files',
validate: function(value) {
if (value.length > 3) {
return false;
}
return true;
}
});
});
The field validator function can also be asynchronous:
fd.spRendered(function() {
fd.field('Email').addValidator({
name: 'MyCustomValidator',
error: 'This email is already taken, try another one.',
validate: function(email) {
// check whether the email exists in another list using PnPjs
return pnp.sp.web.lists.getByTitle('Contacts').items.filter("Email eq '" + email + "'").get().then(function(i) {
if (i.length > 0) {
return false;
} else {
return true;
}
});
}
});
});
You can validate fields once value of another field changes:
fd.spRendered(() => {
function validateFields() {
if (fd.field('Status').value === 'Finished') {
// Make sure that fields have values if set as required, and check for custom validators
fd.field('StartDate').validate();
fd.field('DueDate').validate();
}
}
// Calling validateFields when the Status value changes
fd.field('Status').$on('change',validateFields);
});
Set field to required state if conditions are meant:
fd.spRendered(() => {
function setDueDateRequired() {
if (fd.field('StartDate').value) {
// Set Due Date required
fd.field('DueDate').required = true;
} else {
// Set Due Date as not required if there is no Start Date
fd.field('DueDate').required = false;
}
}
// Calling setDueDateRequired when the Start Date value changes
fd.field('StartDate').$on('change',setDueDateRequired);
// Calling setDueDateRequired on form loading
setDueDateRequired();
});
Button, Hyperlink, and Image controls can execute code when on click. Add code to the control’s Click property, and it will be executed when a user clicks the control.
This can be used for variety of purposes and you don’t need to include JavaScript inside fd events as by the time the button has loaded, other fields have already loaded as well.
Add this code inside the Click property for the Button control to change the Title field value:
fd.field('Title').value = 'Hello, world!'
For the Hyperlink and Image controls, add event.preventDefault() before the rest of the code to prevent the redirection:
//prevent redirection
event.preventDefault();
alert('Clicked');
When the form opens, you can make requests to an external API and retrieve values from the API. You’ll need to make sure that you have the key if it’s needed and that you follow the instructions from the API developers, but here’s an example of how it can be done with ipapi.co, an API that will help us determine person’s location and IP:
//make a request when the form opens
fd.spRendered(() => {
$.getJSON('https://ipapi.co/json/', function (response) {
fd.field('Location').value = response.city + ', ' + response.region_code + ', ' + response.country_name;
fd.field('IP').value = response.ip;
});
});
If you want to store some data in the browser’s cache, you can use local storage for that. For example, you can save some values while the user is working with one form, then retrieve them when the user opens up another form, like this:
//store values in local storage like this:
localStorage.setItem('value1', 'Hello, world!');
localStorage.setItem('value2', fd.field('Title').value);
//retrieve values from local storage
fd.spRendered(() => {
var value1 = localStorage.getItem('value1');
var value2 = localStorage.getItem('value2');
if(value1){
fd.field('Text1').value = value1;
localStorage.removeItem('value1');
}
if(value2){
fd.field('Text2').value = value2;
localStorage.removeItem('value2');
}
});
You can also store all of the form’s data and populate form with same values when it’s opened again, like this:
//save form data before save
fd.spBeforeSave(() => {
localStorage.setItem('form-data', JSON.stringify(fd.data()));
});
//populate form data when form opens
fd.spRendered(() => {
var data = JSON.parse(localStorage.getItem('form-data'));
if(data){
fd.data(data);
localStorage.removeItem('form-data');
}
});