Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalise the first letter of each word within a certain class

Is it possible to capitalise the first letter of each word in a certain class name using jQuery / javascript? I just want to capitalise the first letter of each word of all the fields marked with the class 'capital'.

I just want it to do it as they type, and I know you can do it with css but this is no good as it is stored in the DB as lowercase still.

like image 810
Iain Simpson Avatar asked Dec 02 '22 00:12

Iain Simpson


1 Answers

Here's a simple jQuery plugin that could do this for you:

$.fn.capitalise = function() {
    return this.each(function() {
        var $this = $(this),
            text = $this.text(),
            tokens = text.split(" ").filter(function(t) {return t != ""; }),
            res = [],
            i,
            len,
            component;
        for (i = 0, len = tokens.length; i < len; i++) {
            component = tokens[i];
            res.push(component.substring(0, 1).toUpperCase());
            res.push(component.substring(1));
            res.push(" "); // put space back in
        }
        $this.text(res.join(""));
    });
};

And then call like:

$(".myClass").capitalise();

Here's a working example.

like image 187
jabclab Avatar answered Jan 18 '23 23:01

jabclab