0

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));
     })
 })
}
Yupik
  • 4,932
  • 1
  • 12
  • 26
user7435747
  • 417
  • 2
  • 5
  • 11
  • You can use solution from http://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript – Bizley Apr 05 '17 at 10:17
  • Do you need to display the 'capitalized' text or it is not necessary (it is enough that it is stored in the DB that way)? – gmc Apr 05 '17 at 10:18
  • @gmc I need to automatically display enterted name with uppercase letter. Yes, I could do this with the model, by adding the rule, but instead of auto-replacing it would replace the letters after clicking "Create" button – user7435747 Apr 05 '17 at 10:20
  • @Bizley Somehow my code has to work, because it already worked when I did the same task without Yii, just only by using OOP – user7435747 Apr 05 '17 at 10:21

1 Answers1

2

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

 })
gmc
  • 3,910
  • 2
  • 31
  • 44