Capitalize Words as you type


/ Published in: JavaScript
Save to your folder(s)

Nick Baker


Copy this code and paste it in your HTML
  1. //this will force a capitalize of the first character of each word on input
  2. //this function is meant to be update dynamically as the user types
  3. //example:
  4. // <input .... onkeypress="capMe(this)" ..... >
  5. function capAll(obj){
  6. var val = obj.value;
  7. var val = toArray(val); //old function
  8. var newVal = '';
  9.  
  10. var cap_it = true;
  11. for(var i = 0; i < val.length; i++){
  12. if(cap_it){
  13. newVal += val[i].toUpperCase();
  14. cap_it = false;
  15. }
  16. else{
  17. newVal += val[i];
  18. if(val[i] == ' ') cap_it = true;
  19. }
  20. }
  21.  
  22. obj.value = newVal;
  23. }
  24.  
  25.  
  26. //takes a string and converts it to an array of characters
  27. function toArray(string){
  28. var len = string.length;
  29. var array = new Array();
  30. for(var i=0; i < len; i++){
  31. array[i] = string.charAt(i);
  32. }
  33. return array;
  34. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.