Search code examples
javascriptjqueryinputcapitalize

Javascript: input box - autocapitalize first letter but can override


I have a name input box. I would like to auto-capitalise the first letter of the name as the user types, but allow the user to override the change for names such as "de Salis".

I see here that this is impossible with CSS, because text-transform:capitalize; will capitalise every word and can't be overridden.

A .keyup handler can fix up the first letter as you type, and there are a bunch of solutions found here to do that.

What I can't see how the original capitalisation can be overriden easily. I guess I need a flag, but if the function is one that can be attached to multiple elements, where should the flag live? I could append a DOM element as a flag, but this seems pretty ugly.

A fiddle of the non-override model is found here.

Suggestions?


Solution

  • To have the input box show only the first capital letter, you can use the keyCode directly, as that is always in uppercase format.

    That alone will alleviate the requirement for expensive regex and .replace() methods your using.

    jQuery:

    $('.auto').one('keyup', function(e) {
        $(this).val(String.fromCharCode(e.keyCode));
    });
    

    Reference: jsFiddle


    The following answer has been revised to include Tab Key requirements, clicking inside of input box and pasting via context-menu, using keyboard paste method (Ctrl + V), and directly typing into it. It does away with the character keyCodes so international support is acknowledged. The jQuery selector was obtained here.

    RE-Revised: jsFiddle (Does not force capital letter on submit.)