Search code examples
jquerytextboxcapitalize

Capitalize first letter in textbox


I am using the following code to capitalize the first letter entered into a text box. This works fine at first, but if the entire box is deleted, after typing again it will not capitalize again.

Can this be fixed?

$(function () {
    $('.userBox').one('DOMAttrModified textInput input keypress paste focus', 
          function (e) {
             $(this).val($(this).val().slice(0, 1).toUpperCase() + 
                    $(this).val().slice(1));
          });
});

jsfiddle: http://jsfiddle.net/VBXbz/

updated jsfiddle: http://jsfiddle.net/VBXbz/8/


Solution

  • You want on, not one:

    $(function () {
        $('.userBox').on('DOMAttrModified textInput input keypress paste focus', function (e) {
            $(this).val($(this).val().slice(0, 1).toUpperCase() + $(this).val().slice(1));
        });
    });
    

    one is for handlers you want executed at most once