Search code examples
javascripthtmlchromiumwebview2

Keypress text is not passed to the textarea element


I have a text area element that has a keypress event handler assigned to it. The point of the keypress event handler function is to enforce a character limit on the text area.

When I click in the text area in the browser, I get the cursor, and if I start typing, I'll hit the breakpoint in the JavaScript where the keypress event handler lives. No exceptions get thrown by that handler, but once the function completes, the character that I typed doesn't show up in the text area.

This is happening in a webview2 browser for a desktop app, and also occurs if the web app component is displayed directly in Chrome or Edge.

If I remove the keypress event handler from the text area element, I am able to type in the text area.

function maxLengthKey(field, maxChars) {
  event.returnValue = false;

  if (field.value.length >= maxChars) {
    alert("too many characters.");
    return false;
  } else {
    event.returnValue = true;
  }
}
<textarea name="textArea1" rows="2" cols="20" id="textArea1Notes" tabindex="18" onkeypress="return maxLengthKey(this, 800);"></textarea>


Solution

  • The answer is that setting event.returnValue = false is preventing the event from bubbling up to any other event handlers.

    It is the "old-school" equivalent of event.preventDefault(). See this link https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue