I need to be able to count the textbox characters on a keypress, how would I do that?

Dani AI

Generated

The replies from , and show the basic idea: check the text length and handle line breaks and ranges. For browser JavaScript, though, use the DOM input event (it captures typing, IME composition, pastes and drops) instead of keypress, and prefer the HTML maxlength attribute when you only need to enforce a limit. See MDN on the input event and maxlength.

A practical pattern: listen for input, update a visible counter, and enable the next control only when the length is inside your range. Example (client-side logic; IDs are illustrative):

const txt = document.getElementById('txtUser');
const next = document.getElementById('nextField');
const counter = document.getElementById('countDisplay');

txt.addEventListener('input', () => {
  const len = countGraphemes(txt.value); // robust character count below
  counter.textContent = len + ' / 20';
  next.disabled = !(len >= 4 && len <= 20);
});

Counting characters correctly for modern text requires attention to Unicode: string.length counts UTF-16 code units, so some emoji or accented characters can look like multiple units. Use Intl.Segmenter where available or fall back to code-point-aware splitting:

function countGraphemes(s) {
  if (typeof Intl !== 'undefined' && Intl.Segmenter) {
    return Array.from(new Intl.Segmenter(undefined, {granularity: 'grapheme'}).segment(s)).length;
  }
  return Array.from(s).length; // reasonable fallback for most cases
}

Additional notes: normalize or strip newlines if you want them excluded (e.g., value.replace(/\r\n/g, '\n')), validate again on the server, and consider a polyfill or a small library (for example, the grapheme-splitter project) for full grapheme-cluster accuracy: https://github.com/orling/grapheme-splitter.

Recommended Answers

All 6 Replies

You could use textbox.Text.Lenght. If you have a multiline textbox, use the Lines property wich return an array of strings.

You could use textbox.Text.Lenght. If you have a multiline textbox, use the Lines property wich return an array of strings.

If you have a multi-line textbox, use

length = textBox1.Text.Replace(Environment.NewLine, "").Length;

So like this? if (txtUser.Text.Length.ToString() == "4")

Could be but it's a bit overkill.
Better use: if (txtUser.Text.Length == 4)

If were going to make it so another is enabled after 4 character would I use

if (txtUser.Text.Length == 4<20)

Not completely sure what you're after but if you want to check if it's between 4 and 20 you could use:

if (txtUser.Text.Length >= 4 && txtUser.Text.Length < 20)
            {

            }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.