Discussions

Web tier: servlets, JSP, Web frameworks: How 2 convert strings to CAPS in Javascript as user enters dats?

  1. Hi !
       I have a unique problem.. I need to convert data entered in a text box to be displayed in CAPS. This has to be done real time... I mean, if a user enters a text - my test message, the string has to be converted into MY TEST MESSAGE and this has to be done after the user enters each character(alphabet).

    If anybody has any idea, pls do let me know..

    Thanks in advance,
    -PPuthran
  2. <form>
    <textarea name="testField"
              onkeyup="this.value = this.value.toUpperCase()"></textarea>
    </form>

    No the "onkeyup" event handler is relative recent, so there are no guarantees that this will work on older browsers. I think it will work on Mozilla, Netscape 6+ and IE 4+.
  3. Hi Paul !
      Thanks for the reply but I did try this solution. When I try to edit the entered data, the cursor is forced back to the end of the string.
    example, if I enter abcdeg and try to go back by hitting the left key to enter f before the g, then the cursor is forced back the end of the string.
    I am using IE 5.5.

    Thanks,
    -Paresh
  4. That is the problem with all the key-based events in Javascript; they are very flaky. As a rule I don't use them.

    I suggest you use the onchange event instead, to convert to ALLCAPS after the user leaves the field. In practice, the effect is the same. Also, it is much less buggy and much more browser-independent.
  5. Hi !

    >    I have a unique problem.. I need to convert data entered in a text box to be displayed in CAPS.

    This isn't really unique - we do it all the time in the midrange world. To do it properly, you need modifieable events, which are only available in the IT DOM. If you're willing to stick with IE, here's a simple toUpper() function:

    function toUpper()
    {
      key = window.event.keyCode;
      if ((key > 0x60) && (key < 0x7B)) window.event.keyCode = key-0x20;
    }

    Connect this to the onKeyPress event.