The CreatorCon Call for Content is officially open! Get started here.

How to set form focus on mandatory fields if not filled?

Anish Reghu
Kilo Sage

Hello Experts,

 

As a urgent requirement, I want the form focus to be on the mandatory fields which are left empty on Save/Submit.

Lets's say field A, B, C are on the 3rd tab in the form section of a form.

And I came to the 1st tab to fill in X and Y fields. I forget to fill in A, B, C and try to save.

Of course A, B, C being mandatory would be prompted to be filled in, but how do I set my form focus on those fields?

 

Code: UI Script - Condition if true:

===============================

function onCondition() {
var arr = g_form.getMissingFields();
alert(arr);
var ele;
setTimeout(setFocus(),0); //tried calling function as (setFocus,0) as well.

function setFocus()
{
for(var i=0; i<arr.length; i++)
ele = document.getElementById(arr[i]);
ele.focus();

}

}

 

Please help, urgent!

1 ACCEPTED SOLUTION

Anish Reghu
Kilo Sage
If you would like to avoid your end users to keep finding those missed mandatory fields on a form during submission, try this CS:



function onSubmit() {

 var mandatoryFields = g_form.getMandatoryFields();

 for (var i = 0; i < mandatoryFields.length; i++) {

  var fieldName = mandatoryFields[i];

  if (g_form.getValue(fieldName) == '') {

   g_form.addErrorMessage(fieldName, 'This field is required.');





   g_form.showFieldMsg(fieldName, true);

   if (i == 0) {

    g_form.setFocusOnField(fieldName);

   }

  }

 }

}

View solution in original post

3 REPLIES 3

Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hello,

 

You may find the below thread helpful.

https://community.servicenow.com/community?id=community_question&sys_id=708ff2e9db58dbc01dcaf3231f961900

 

Thanks,

Pradeep Sharma

Anish Reghu
Kilo Sage

Thanks I had checked this. But the only thing that is not working for me is that focus() does not navigate within the form section if there are mandatory fields empty within the form section tabs.

Anish Reghu
Kilo Sage
If you would like to avoid your end users to keep finding those missed mandatory fields on a form during submission, try this CS:



function onSubmit() {

 var mandatoryFields = g_form.getMandatoryFields();

 for (var i = 0; i < mandatoryFields.length; i++) {

  var fieldName = mandatoryFields[i];

  if (g_form.getValue(fieldName) == '') {

   g_form.addErrorMessage(fieldName, 'This field is required.');





   g_form.showFieldMsg(fieldName, true);

   if (i == 0) {

    g_form.setFocusOnField(fieldName);

   }

  }

 }

}