2

I'm using this code:

     function ucfirst(field) {
       field.value = field.value.substr(0, 1).toUpperCase() +       field.value.substr(1);
}

this is working if i have a city like california ==> California. But if I have new york it will not convert the first letter.

Any tips how to make this code work?

abagh0703
  • 841
  • 1
  • 12
  • 26
doudy_05
  • 61
  • 4

4 Answers4

2

If you're looking for a JavaScript function, here's one from Greg Dean

function ucfirst(field)
{
    var fieldString = field.value;
    fieldString = fieldString.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    field.value = fieldString;
}

Edit: Added Fievel Yaltsen's suggestion to use field.value instead of return.

And here's a JSFiddle

Community
  • 1
  • 1
abagh0703
  • 841
  • 1
  • 12
  • 26
0

Why javascript if you can do it with css?

p {
  text-transform: capitalize;
}
<p>california, new york</p>
Nick
  • 3,231
  • 2
  • 28
  • 50
0
function ucfirst(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
Daath
  • 1,899
  • 7
  • 26
  • 42
  • when I use this code I have this error Uncaught TypeError: Cannot read property 'replace' of undefined – doudy_05 Oct 12 '15 at 16:35
  • 3
    Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. – SuperBiasedMan Oct 12 '15 at 17:02
0
    <!DOCTYPE html>
<html>
<head>
<style>
p.capitalize {
    text-transform: capitalize;
}
</style>
</head>
<body>
<p class="capitalize">This is some text.</p>

</body>
</html>
Asif Mehmood
  • 473
  • 3
  • 16
  • 1
    Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. – SuperBiasedMan Oct 12 '15 at 17:01