Copy link to clipboard
Copied
I have a text field of first_name and one of last_name. I want to make sure not matter what format the user inputs the the first letter is Capitalized and the rest is lower case. Can someone tell me how this is done? Thanks!
Copy link to clipboard
Copied
javascript
<html>
<head>
<script type="text/javascript">
function capitalize(form) {
value = form.value;
newValue = '';
value = value.split(' ');
for(var i = 0; i < value.length; i++) {
newValue += value.substring(0,1).toUpperCase() +
value.substring(1,value.length) + ' ';
}
form.value = newValue;
}
</script>
</head>
<body>
<form name="testform">
<input type="text" name="testinput" onBlur="capitalize(this)">
</form>
</body>
</html>
Copy link to clipboard
Copied
The best method is to use CSS to capitalize the first letter in the span id when displaying the name.
Javascript method will not work for users that have javascript disabled in their browser.
Copy link to clipboard
Copied
follow up note:
you must use javascript or a combination of javascript and php, to convert their names in real time ( i.e. as soon as they enter the data and move to the next text field, it will correct their input). PHP, although the best solution, would still be after the form is processed. Very few people do not use javascript in their browsers, and you can use both javascript to change on fly and then php to catch those that don't use it (which should be done in all cases). If you know a way in css to do that, please post. My understanding is CSS text transform only works on content on load and no in real time. Personally, I'd focus on the post process and use PHP as DP has posted, but if it's real time you're looking for, javascript is it.
Copy link to clipboard
Copied
Rick4209 wrote:
I have a text field of first_name and one of last_name. I want to make sure not matter what format the user inputs the the first letter is Capitalized and the rest is lower case. Can someone tell me how this is done? Thanks!
It depends on what you want to do with the name. If this is for inserting the name in a database and you're using PHP, it's very simple:
$name = 'DaVID';
$formatted = ucfirst(strtolower($name));
echo $formatted; // outputs 'David'
This nests two functions: the inner function, strtolower(), converts everything to lowercase, and the outer function, ucfirst(), converts the first letter to uppercase.