Setting maximum character length for variables of multiline text

VinyaP
Tera Contributor

Hi Team,

Can anyone help me please. Iam using this script working in native UI but not in Portal.

function onLoad() {
    var control = g_form.getControl('service_description');
    //Set its onkeyup method
    control.onkeyup = isMaxLength;

}


function isMaxLength() {
    var mLength = 170;
    var control = g_form.getControl('service_description');
    if (control.value.length > mLength) {
        g_form.hideErrorBox('service_description');
        g_form.showErrorBox('service_description', 'You have reached the maximum character limit for this field.');
        control.value = control.value.substring(0, mLength);
    } else {
        g_form.hideErrorBox('service_description');
    }
}
but getcontrol method not working in portal
4 REPLIES 4

HrishabhKumar
Kilo Sage

Hi @VinyaP ,

In ServiceNow, the getControl method is not supported in Service Portal. Instead, you need to use g_form.getElement() or jQuery to interact with form elements in Service Portal. Here is how you can modify your script to work in both the native UI and Service Portal:

  1. Use g_form.getElement() to get the field element.
  2. Attach the keyup event listener using jQuery.

Here's how you can modify your script:

 

 

function onLoad() {
    var control = g_form.getElement('service_description'); // Use getElement for Service Portal
    // Set its onkeyup method using jQuery
    $(control).on('keyup', isMaxLength);
}

function isMaxLength() {
    var mLength = 170;
    var control = g_form.getElement('service_description');
    if (control.value.length > mLength) {
        g_form.hideErrorBox('service_description');
        g_form.showErrorBox('service_description', 'You have reached the maximum character limit for this field.');
        control.value = control.value.substring(0, mLength);
    } else {
        g_form.hideErrorBox('service_description');
    }
}

 

 

 

Thanks,

Hope this helps.

If my response proves helpful please mark it helpful and accept it as solution to close this thread.

Still not working... I have tried that as well. Getting java script console error.

Tai Vu
Kilo Patron
Kilo Patron

Hi @VinyaP 

You can consider to have an OnChange Client Script to handle max length input for that multiple line text variable.

Sample script below.

 

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    g_form.hideFieldMsg('justification', true);
	var max_length = 5;

    if (newValue.length > max_length) {
        g_form.setValue('justification', newValue.slice(0, max_length));
        g_form.showFieldMsg('justification', 'Maximum length is 5', 'error');
    }

}

 

 

Cheers,

Tai Vu

VinyaP
Tera Contributor

Hi Timi

 

But it is deleting whatever user entered if it is beyond the limit.it should not be the case.onkey we need to stop the user to enter.