When creating forms, users often don’t bother capitalizing the first letters of names, cities, or other proper nouns, which can look untidy when displayed from the database. As a good programmer, you can fix this by ensuring the first letter of each word is automatically capitalized. This can be done easily using a function like ucwords in many programming languages, which converts the first letter of each word in a string to uppercase, making the data look clean and professional.
In PHP, the first letter of every Word is very simple by a PHP universal function:
$str = "hello world";
$result= ucwords($str);
echo $result; // output: Hello World
Most of the cases, we have to change the value of Field of the form instantly, so we have to convert the string value into ucwords using JavaScript or jQuery. Here are the main code for ucwords.
function ucwords(str) {
return str.split(' ').map(function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}).join(' ');
}
In HTML form, call the function directly from the field when start write:
<input type="text" name="name" id="name" onInput="ucwords(this.value);">
You can call the ucwords function vide JavaScript through ids of the fields:
<input type="text" name="name" id="name" >
<input type="text" name="city" id="city" >
<input type="text" name="address" id="address" >
<script>
const ids = ['#name', '#city', '$address'];
$(ids.join(', ')).on('input', function() { this.value = ucwords(this.value);});
</script>
recent comments