Razgriz
Razgriz

Reputation: 7343

"Title Case" in textfields using onKeyUp and RegEx

I am building a web application and I want my textfields to be title case. I did my research and found that you can do the following code on the textfield's onKeyUp controller:

onTextfieldKeyup1: function(textfield, e, eOpts) {

    var str = textfield.getValue();

    var newIn =  str.replace(/\w\S*/g, function(txt){
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });

    textfield.setValue(newIn);
}

This works, the first letter gets capitalized properly.

However, I also want to be able to select/highlight everything when I select/tab into the field. I know I can achieve this by doing: selectOnFocus: true.

The issue with the RegEx solution is that it filters every single keystroke so when I tab into the textview, it does not select everything, instead, it runs the RegEx and my insertion point for the text is at the end. Also, it does not allow inputs like LeBron or MacArthur as it only capitalizes the first letter and lower cases everything else.

I am using ExtJS 4.

Upvotes: 0

Views: 341

Answers (2)

Christophe Le Besnerais
Christophe Le Besnerais

Reputation: 4693

you should listen to a different event like change or blur.

Also you can use Ext.String.capitalize instead of the regexp.

(http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.String-method-capitalize)

Upvotes: 1

Moishe Lipsker
Moishe Lipsker

Reputation: 3032

You could check in your event if the key is not the tab key

    if (e.keyCode != 9) {
        var str = textfield.getValue();

        var newIn =  str.replace(/\w\S*/g, function(txt){
            return txt.charAt(0).toUpperCase() + txt.substr(1);
        });

        textfield.setValue(newIn);
    }

Upvotes: 1

Related Questions