简体   繁体   中英

Capitalizing first letters in JavaScript

I have a problem here. I just started learning with Yii2 and I need to capitalize first letters of my entry form (it's name and surname). I'm doing this with JS, but somehow my code does not work and it didn't printing any results. Could someone help me to solve this problem and tell me what I'm doing wrong?

Here is my code:

function entryForm(name, surname) {
this.name = $(name);
this.surname = $(surname);
var self = this;

/*
* Capitalizes first letter of users entered name and surname
*
* @param string input
*/
this.capitalizeName = function(input) {
var name = input.val();
name = name.toLowerCase().replace(/(^|\s)[a-z]/g, function(letter) {
    return letter.toUpperCase();
})
input.val(name);
}
var entryForm = new entryForm('#employee-name', '#employee-surname');

$(document).ready(function() {
/*
* Executes named function
*/
    $('#employee-name, #employee-surname').change(function() {
        entryForm.capitalizeName($(this));
     })
 })
}

I'd made a couple adjustments that I think I'd make it work:

First, name your js 'class' starting with an uppercase. This variable declaration var entryForm = new entryForm( shadows the previous declaration of the 'class' with the same name.

Second, I'd put the $(document).ready function outside of the class.

function EntryForm(name, surname) {
    this.name = $(name);
    this.surname = $(surname);
    var self = this;

    /*
    * Capitalizes first letter of users entered name and surname
    *
    * @param string input
    */
    this.capitalizeName = function(input) {
        var name = input.val();
        name = name.toLowerCase().replace(/(^|\s)[a-z]/g, function(letter) {
            return letter.toUpperCase();
        })
        input.val(name);
    }   
}

$(document).ready(function() {
/*
* Executes named function
*/
    $('#employee-name, #employee-surname').change(function() {
        var entryForm = new EntryForm('#employee-name', '#employee-surname');
        entryForm.capitalizeName($(this));
     })

 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM