Title the first letter of each word in a particular class

Is it possible to use the first letter of each word in the name of a particular class using jQuery / javascript? I just want to make amends for the first letter of each word in all fields marked with the capital class.

I just want it to be executed as they are input, and I know that you can do it with css, but this is not good, since it is stored in the database in lower case.

+3
source share
7 answers

Here is a simple jQuery plugin that can 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:

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

Here is a working example .

+6
source

The solution looks something like this:

: 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));
});
+5

- :

$('.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);
}
+2

, :)

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

+1

css text-transform: capize, , .

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

:

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

You could do something like this. This will use the text in the text box 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 += ' ';
            }
        } 
        $(this).val(result); 
    })
});

Here you can see the working script: http://jsfiddle.net/5dMg7/

-1
source

Source: https://habr.com/ru/post/1016979/


All Articles