Skip to content Skip to sidebar Skip to footer

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 fie

Solution 1:

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

$.fn.capitalise = function() {
    returnthis.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.

Solution 2:

The solution is something like this:

Working Sample: http://jsfiddle.net/Py7rW/7/

$('.captial').each(function(){
    var arr = $(this).text().split(' ');
    var result = "";
    for (var x=0; x<arr.length; x++)
        result+=arr[x].substring(0,1).toUpperCase()+arr[x].substring(1)+' ';
    $(this).text(result.substring(0, result.length-1));
});

Solution 3:

I think this will work :)

$('.capital').css("text-transform","capitalize");

Solution 4:

You can try something like:

$('.capital').each(function() {
    var s = $(this).text().split(' ');
    for(var i=0; i<s.length; i++) {
        s[i] = s[i].substring(0,1).toUpperCase() + s[i].substring(1);
    }
    s = s.join(' ');
    $(this).text(s);
}

Solution 5:

I would use the css text-transform:capitalize to avoid having to run this on every keypress, and change the actual value of the fields on change.

field.value= field.value.replace(/((^| )[a-z])/g, function(a, b){
    return b.toUpperCase();
});

Post a Comment for "Capitalise The First Letter Of Each Word Within A Certain Class"