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.



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 = [],
        for (i = 0, len = tokens.length; i < len; i++) {
            component = tokens[i];
            res.push(component.substring(0, 1).toUpperCase());
            res.push(" "); // put space back in

And then call like:


Here's a working example.


The solution is something like this:

Working Sample:

    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));

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(' ');

I think this will work :)



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();

Simple Step to capitalize the first letter of each word :

$(document).on('keyup', '#myText', function () {
    this.value = this.value.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});

You could do something like this. This will capitalize the text in a textbox whenever the text has changed:

$(document).ready(function() {
    $('.capital').change(function() {
        var arr = $(this).val().split(' '); 
        var result = ""; 
        for (var i=0; i<arr.length; i++){ 
            result += arr[i].substring(0,1).toUpperCase() + arr[i].substring(1);
            if (i < arr.length-1) {
                result += ' ';

You can see a working fiddle here:


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.