Skip to content

Commit 8e89998

Browse files
authored
Display a Live Word Count for Description Field (#2050)
* Create code.js * Create README.md * Update code.js * Updated 2 code.js
1 parent a074bed commit 8e89998

File tree

2 files changed

+16
-0
lines changed
  • Client-Side Components/Client Scripts/Display a Live Word Count for Description Field

2 files changed

+16
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
The script enhances a form field (specifically the description field) by:
2+
-Adding a live word counter below the field.
3+
-Visually warning the user if the word count exceeds 150 words.
4+
5+
This client-side script, intended for use in a ServiceNow form (e.g., catalog item or incident form), dynamically appends a custom `<div>` element below the `description` field to display a real-time word count. It leverages the `g_form.getControl()` API to access the field's DOM element and attaches an `input` event listener to monitor user input. The script calculates the word count by splitting the input text using a regular expression (`\s+`) and updates the counter accordingly. It applies conditional styling to the counter (`green` if ≤150 words, `red` if >150), providing immediate visual feedback to the user to enforce input constraints.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
2+
if (isLoading || newValue === oldValue) {
3+
return;
4+
}
5+
6+
var wordCount = newValue.trim().split(/\s+/).length;
7+
var message = 'Word Count: ' + (newValue ? wordCount : 0);
8+
var messageType = (wordCount > 150) ? 'error' : 'info';
9+
10+
g_form.showFieldMsg('description', message, messageType);
11+
}

0 commit comments

Comments
 (0)