Change input value in form with jQuery

Hi!

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.

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

Javascript

$(document).ready(function(){
        var forename = $("#user_forenamne");
       
        forename.blur(validateForename);
       
        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
                $("#user_forename").val("name");
        }
});
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

Comments

  • Proper way would be:
    $(document).ready(function(){
            $("#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
                $(this).val(name);
            });
        });
    </body>
    </html>
    
Sign In or Register to comment.