Count number of characters of a field dynamically

kavyagande
Tera Contributor

on incident form, for resolution notes we have to count number of characters entered.

we can do this through a client script (on change)

but the issue is, i want to calculate number of characters while entering the value in the filed.

4 REPLIES 4

Deepak Ingale1
Mega Sage

You can use the onkeyup event and check the field length.

 

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onkeyup 

felladin
Tera Guru

Hi,

 

I think you are looking for this:

https://docs.servicenow.com/bundle/jakarta-platform-administration/page/administer/reference-pages/task/t_TextFieldCharacterCounter.html

Ct111
Giga Sage

Hi kavyagande,

 

You can create an onChange client script for the field whose length you want to be displayed 

 


var k = g_form.getValue('u_thirst');    // Enter the name of your fields 
 
g_form.showFieldMsg("u_thirst", "Hello World"+k.length, "error");        // for displaying Msg below the field so that v can check it's length.

 

 

Please Mark my Answer as Helpful if it served your purpose

 

Hitoshi Ozawa
Giga Sage
Giga Sage

 Hi Kavyagande,

Following script will count the number of characters entered in Resolution notes field and show a warning if the total count is more than specified number of characters. The script currently will only work in UI and not in Service Portal because .getControl() is only supported in UI.

 

Client script. Change value of "maxLength" to increase/decrease max number of allowable characters.

function onLoad() {
    var fieldName = 'close_notes';  // name of multiline text field
    var maxLength = 5;  // max length of multiline text field
	try {
        var control = g_form.getControl(fieldName);
        control.onkeyup = function isMaxLength() {
            var control = g_form.getControl(fieldName);
            if (control.value.length > maxLength) {
                g_form.hideErrorBox(fieldName);
                try {
                    g_form.showFieldMsg(fieldName, 'Please limit number of characters to ' + maxLength + ' characters.', 'error');
                } catch (e) {}
                control.value = control.value.substring(0, mLength);
            } else {
                g_form.hideErrorBox(fieldName);
            }
        };
    } catch (e) {
        alert(e.message);
    }
 }

Execution result:

find_real_file.png