11

Possible Duplicate:
Capitalize the first letter of string in JavaScript

This is may code so far. I would like the FIRST_Name and LAST_Name fields to capitalize the first letter and have all other letters small:

Also, I am unfamiliar with javaScript so I am not exactly sure what I am doing.

latest edit. What is wrong with this code?

    <HTML>
<HEAD>
<TITLE></TITLE>
<script language="javascript" type="text/javascript">
<!--
function CheckForm()

formObj.FIRST_Name.value = titleCase(formObj.FIRST_Name.value);
formObj.LAST_Name.value = titleCase(formObj.LAST_Name.value);

function titleCase(str) {
    var words = str.split(/\s+/);
    for (var i=0; i<words.length; i++)
        words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
    return words.join(" ");
}


{
  var formObj = document.getElementById("Data");
  var firstname = formObj.FIRST_Name.value;
  var lastname = formObj.LAST_Name.value;


    if(notEmpty(formObj.FIRST_Name, "Please enter your first name")){       
    if(notEmpty(formObj.LAST_Name,"Please enter your last name")){  
    if(titleCase(formObj.FIRST_Name)            

    return true;}}

    return false;
    }

function notEmpty(elem, helperMsg){
    if(elem.value.length == 0){
        alert(helperMsg);
        elem.focus(); // set the focus to this input
        return false;
    }
    return true;
}


</script>
</HEAD>
<BODY>
<div style="background: #CCCC99">
<HR><FORM id="Data" onsubmit="return CheckForm()" action="post to server" method=post>
<P>First Name: <input type=text name=FIRST_Name maxlength=15 size=15>
   Last Name:  <input type=text name=LAST_Name maxlength=15 size=15></P>
<input type=submit value="Submit Products Registration Form" style="width: 220px"><input type=reset value="Reset">
</form>
</div>
</BODY>
</HTML>
Community
  • 1
  • 1
The Count
  • 171
  • 1
  • 3
  • 12
  • It's simpler to use this regular expression: `/\b\w/g` then just replace the match (a single character) with the upper-case version. `\b` means "word boundary". (It will even work across hyphens, which may or may not be desirable :-) –  Jul 26 '12 at 01:45
  • 1
    @pst - Allowing for white-space at the beginning is a good idea and `\b` should do that, but the original code also changes the rest of the text to lowercase. – nnnnnn Jul 26 '12 at 02:16
  • What exactly do you want to do? Check whether the input is in the correct format (and alert)? Correct it when submitting (then serverside would be OK as well)? Correct live while typing (very annoying)? – Bergi Jul 26 '12 at 02:22
  • The `titleCase()` function added when you edited the question will not work (it has an error: `pieces` is not defined - should be `words`). – nnnnnn Jul 26 '12 at 02:24
  • Just fixed that in an edit. Sorry... – dykeag Jul 26 '12 at 02:27

5 Answers5

5

Try this:

String.prototype.toCap = function()
{ 
   return this.toLowerCase().replace(/^.|\s\S/g, function(str) { 
       return str.toUpperCase(); 
   });
}        

var firstname = "gob".toCap();
var lastname = "bluth".toCap();

alert(firstname + ' ' + lastname);
4

For those of us who are scared of regular expressions (lol):

function titleCase(str)
{
    var words = str.split(" ");
    for ( var i = 0; i < words.length; i++ )
    {
        var j = words[i].charAt(0).toUpperCase();
        words[i] = j + words[i].substr(1);
    }
    return words.join(" ");
}
dykeag
  • 554
  • 3
  • 11
3

Try this code:

function toTitleCase(str){
    var words = str.match(/\w*/g);
    for(var i=0;i<words.length;i++)
        words[i] = words[i][0].toUpperCase() + words[i].slice(1);
    return words.join(' ');
}
toTitleCase('my name');
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
3

"don't know how to put it into my code"

Copy the titleCase() (or toTitleCase() or whatever you are calling it now) function into your script block, and then add the following code just before the if statements in your CheckForm() function:

formObj.FIRST_Name.value = titleCase(formObj.FIRST_Name.value);
formObj.LAST_Name.value = titleCase(formObj.LAST_Name.value);

That way at the point where the form is submitted the fields will be changed using your toTitleCase() function. (If you add the code before the if statements the fields will be changed regardless of whether the notEmpty() validations pass, which seems reasonable to me.)

(Incidentally, the firstname and lastname variable declarations can be deleted from the CheckForm() function because you don't ever use those variables.)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Well as I commented above, the `titleCase()` function you edited into your question has an error in it (which has since been fixed in dykeag's answer). And as I said in my answer, the change to the values would only happen on submit - but to me that seems OK and you didn't specify otherwise. – nnnnnn Jul 26 '12 at 02:33
3

To uppercase a single string see How do I make the first letter of a string uppercase in JavaScript?.

If you want to to this on every word in the string, you will want to split the string into words, apply the ucFirst function on each of them and join them back together:

function titleCase(str) {
    var words = str.split(/\s+/);
    for (var i=0; i<words.length; i++)
        words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
    return words.join(" ");
}

Or you can apply a regex on them, to match every first letter and replace them:

function titleCase(str) {
    return str.replace(/\b\S/g, function(c){
        return c.toUpperCase();
    });
}

At your latest edit: You've got an syntax error in the third if-condition, it lacks a closing bracket. Also, you've inserted the titleCase code before the function body.

/* the titleCase function from above here */

function CheckForm() {
    var formObj = document.getElementById("Data");
    var firstname = formObj.FIRST_Name;
    var lastname = formObj.LAST_Name;

    firstname.value = titleCase(firstname.value);
    lastname.value = titleCase(lastname.value);

    return notEmpty(firstname, "Please enter your first name")
      && notEmpty(lastname, "Please enter your last name");
}

function notEmpty(elem, helperMsg){
    if(elem.value.length == 0){
        alert(helperMsg);
        elem.focus(); // set the focus to this input
        return false;
    }
    return true;
}

My personal view on this: Don't try to correct the names with JavaScript at all. You do it when the form is committed, and the user will see effects of this action only if he left one input empty and encounters the error message.

You need to do this anyway serverside (never trust user input / POST data, javascript could be disabled), so if you aren't familiar with JavaScript (or don't like it or whatever), just omit this "feature".

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375