Change input value in form with jQuery


I'm trying to help my user when they use my forms. The things I would love to do is to trim the value (strip leading and trailing spaces) and make first letter in every word capital. This is what I've came up with so far.

<input id="user_forenamne" name="user_forenamne" type="text"/>


        var forename = $("#user_forenamne");
        function validateForename(){
                var name = $("user_forename").val;
                //strip leading and trailing spaces
                name = $.trim(name)
                //change first letter in every word to uppercase
                name = Capital(name);
                //update input field whit new value
function Capital(value) {
  if (value != "") {
    var firstLetter = value.substring(0, 1).toUpperCase();
    var restOfWord = value.substring(1, value.length).toLowerCase();
    value = firstLetter + restOfWord;
Does anyone understand why it isn't working or maybe have a better approach to sole this problem.

Many thanks in advance
Adam Nyberg


  • Proper way would be:
            $("#user_forenamne").blur(function () {
                // This line will trim the name
                var name = $.trim($(this).val());
                // Split the words
                var words = name.split(/\s|_/);
                // Capitalize them
                words.forEach(function (e, i) {
                    words[i] = e.substr(0, 1).toUpperCase() + (e.length > 1 ? e.substr(1).toLowerCase() : "");
                // Make new string
                name = words.join(" ");
                // Replace the current name with validated name
Sign In or Register to comment.