Reputation: 487
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));
})
})
}
Upvotes: 0
Views: 399
Reputation: 3990
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));
})
})
Upvotes: 2