How do I capitalize the first letter?

Asked

Viewed 2,929 times

6

I have the function, and it works perfectly:

$.fn.capitalize = function() {
function isTRChar(key) {
    var trchar = [231, 246, 252, 287, 305, 351];
    for (var i = 0; i < trchar.length; i++) {
        if (trchar[i] == key) return true;
    }
    return false;
}

$.each(this, function() {

    var $this = $(this);
    if ($this.is('textarea') || $this.is('input:text')) {
        $this.on({
            keypress: function(event) {
                var pressedKey = event.charCode == undefined ? event.keyCode : event.charCode;
                var str = String.fromCharCode(pressedKey);
                if (pressedKey == 0) {
                    if (!isTRChar(pressedKey)) return;
                }

                this.value = this.value.replace(/\b[a-z]/gi, function($0) {
                    return $0.toUpperCase();
                });
                this.value = this.value.replace(/@([a-z])[\w\.]*\b/gi, function($0, $1) {
                    return $0.substring(0, 2).toUpperCase() + $0.substring(2).toLowerCase();
                });

                if (!this.createTextRange) {
                    var startpos = this.selectionStart;
                    var endpos = this.selectionEnd;
                    if (!$(this).attr('maxlength') ||
                        this.value.length - (endpos - startpos) < $(this).attr('maxlength')) {
                        this.setSelectionRange(startpos + 1, startpos + 1);
                    }
                }
            }
        });
    }
});
}

But it doesn’t work with accent, cedilla and in their own names, of or of also uppercase.

Examples: (what it looks like when typed)

Maria De Fátima

Jose Gonçalves

How to correct this function?

  • 1

    I didn’t want to copy the code and play here, but this link has exactly what you need (http://jsfiddle.net/q8eDW/5/)

  • 1

    Thank you @rLinhares !

4 answers

4


Hello you can try this [editing]: Sorry I didn’t even check back now.

function contains(str, search){
 if(str.indexOf(search) >= 0){
   return true;
 } else {
   return false;
 }
}
$.fn.capitalize = function(str) {
    $.each(this, function() {
        var split = this.value.split(' ');
        for (var i = 0, len = split.length; i < len; i++) {
            var verify = (split[len - 1] == "D" || split[len - 1] == "d") && (str == "e" || str == "E") || (str == "o" || str == "O");
            if (verify == false) {
                if ( contains(split[i], 'de') == false && contains(split[i], 'do') == false) {
		    //alert(split[i]);
                    split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
                }
            }
        }
        this.value = split.join(' ');
    });
    return this;
};
$("textarea").keypress(function(e) {
    var str = String.fromCharCode(e.which);
    $(this).capitalize(str);
});
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 
 <textarea></textarea>

  • First, thank you very much friend! Just did not solve the problem of De and Do.

  • I can’t adapt something to De or Do. =/

  • 1

    See if you can now pfv.

  • Did it work ok? | I made an edit.

  • Perfect friend! Thank you very much!!

  • Nads, rsrs. Can I ask what goal you have to create this application for? Is it for same studies or another goal? I used to do this when studying :D

  • I’m doing a patient registration system from the Popular Pharmacy of my pharmacy! =)

  • 1

    Okay, if it’s in PHP, just ask if you have any questions that I can help :D I’m good at PHP.

  • Lucas, I need a PHP HELP! =)

Show 5 more comments

2

Regular expressions also work, and it only takes one line to solve the problem. The other two are just to take the value of the text box and then to reset its value:

$("textarea").keypress(function(e) {
    var str = $(this).val();
    str = str.replace(/(^|\s|$)(?!de|do|d$)(.)/g, (geral, match1, match2) => match1 + match2.toUpperCase());
    $(this).val(str);
});
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 
 <textarea></textarea>

1

Another possible solution is using map to turn the value into its capitalized and an array of invalid values to capitalize:

const invalidos = ["de", "do"];

$("#capitalizar").on("click", function(){
    let novoTexto = $("#texto")
        .val()
        .split(" ")
        .map(palavra => invalidos.includes(palavra) || palavra.length < 2 ? 
            palavra : 
            palavra.charAt(0).toUpperCase() + palavra.slice(1))
        .join(" ");
 
    $("#texto").val(novoTexto);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="texto">
<input type="submit" value="Capitalizar" id="capitalizar">

  • Thanks for the help also @Isac !

  • 1

    @Guilhermelirio No problem. Good luck in the rest of the development.

-2

<textarea value="" onfocus='document.getElementById("id").style.textTransform = "capitalize";'</textarea>

Using this code works perfectly (Chrome and internet explorer).

  • 1

    You don’t have to do it like this document.getElementById("id") just one this.style.textTransform

Browser other questions tagged

You are not signed in. Login or sign up in order to post.