0

What is the problem with this code? I want Capitalize the first letter of every word

function capitalizeEachWord(str)
{
   var words = str.split(" ");
   var arr = Array();
   for (i in words)
   {
      temp = words[i].toLowerCase();
      temp = temp.charAt(0).toUpperCase() + temp.substring(1);
      arr.push(temp);
   }
   return arr.join(" ");
      var first=document.getElementById(textbox1).value;
       document.getElementById("resualt").innerHTML=arr; 
     }

3 Answers3

0

Try this, if id resualt is correct. I have set fiddler to test.

 document.getElementById("resualt").innerHTML = str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});

Demo

Amit
  • 15,217
  • 8
  • 46
  • 68
0

You are returning from the function before updating the element.

function capitalizeEachWord(str)
{
   var words = str.split(" ");
   var arr = Array();
   for (i in words)
   {
      temp = words[i].toLowerCase();
      temp = temp.charAt(0).toUpperCase() + temp.substring(1);
      arr.push(temp);
   }
   return arr.join(" "); // From now on, it's dead code.
   var first=document.getElementById(textbox1).value;
   document.getElementById("resualt").innerHTML=arr; 
}

Try doing this:

function capitalizeEachWord(str)
{
   var words = str.split(" ");
   var arr = Array();
   for (i in words)
   {
      temp = words[i].toLowerCase();
      temp = temp.charAt(0).toUpperCase() + temp.substring(1);
      arr.push(temp);
   }
   var strCapitalized = arr.join(" "); // Store it in a variable
   var first=document.getElementById(textbox1).value;
   document.getElementById("resualt").innerHTML = strCapitalized; // Use the variable
}
Thiago Negri
  • 5,221
  • 2
  • 28
  • 39
  • Or they could try returning the value, then setting the elements innerHTML property as a separate action while calling that function to get the new value. Then they get a useful function that can be used for setting any element, not one that only updates a single one. – Anthony Grist Nov 18 '14 at 14:13
0

By using jQuery you can do this as shown below:

Demo: https://jsfiddle.net/cxow8198/3/

<input type="text" id="input">

<script>
//usage
$("input").keyup(function() {
   toUpper(this);
});

//function
function toUpper(obj) {
    var mystring = obj.value;
    var sp = mystring.split(' ');
    var wl=0;
    var f ,r;
    var word = new Array();
    for (i = 0 ; i < sp.length ; i ++ ) {
        f = sp[i].substring(0,1).toUpperCase();
        r = sp[i].substring(1).toLowerCase();
        word[i] = f+r;
    }
    newstring = word.join(' ');
    obj.value = newstring;
    return true;   
}
</script>

Query code snippet to make capitals of the first letter of every word in the string. This could be used to prevent users from entering all caps for titles or text when they input data into forms.

Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63