Change input value in form with jQuery

    • 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

      Source Code

      1. <input id="user_forenamne" name="user_forenamne" type="text"/>
      2. Javascript
      3. $(document).ready(function(){
      4. var forename = $("#user_forenamne");
      5. forename.blur(validateForename);
      6. function validateForename(){
      7. var name = $("user_forename").val;
      8. //strip leading and trailing spaces
      9. name = $.trim(name)
      10. //change first letter in every word to uppercase
      11. name = Capital(name);
      12. //update input field whit new value
      13. $("#user_forename").val("name");
      14. }
      15. });
      16. function Capital(value) {
      17. if (value != "") {
      18. var firstLetter = value.substring(0, 1).toUpperCase();
      19. var restOfWord = value.substring(1, value.length).toLowerCase();
      20. value = firstLetter + restOfWord;
      21. }
      Display All

      Does anyone understand why it isn't working or maybe have a better approach to sole this problem.

      Many thanks in advance
      Adam Nyberg

      The post was edited 1 time, last by Ancient Dragon ().

    • Proper way would be:

      JavaScript Source Code

      1. $(document).ready(function(){
      2. $("#user_forenamne").blur(function () {
      3. // This line will trim the name
      4. var name = $.trim($(this).val());
      5. // Split the words
      6. var words = name.split(/\s|_/);
      7. // Capitalize them
      8. words.forEach(function (e, i) {
      9. words[i] = e.substr(0, 1).toUpperCase() + (e.length > 1 ? e.substr(1).toLowerCase() : "");
      10. });
      11. // Make new string
      12. name = words.join(" ");
      13. // Replace the current name with validated name
      14. $(this).val(name);
      15. });
      16. });
      17. </body>
      18. </html>
      Display All