Capitalize first letter using javascript | Sanwebcorner

Capitalize first letter using javascript

This post help you how to set the first letter capital in the sentence not a word. If you want to set the first letter capital in the word means you can use the css code like text-transform: capitalize; but if you want to capitalize the first letter in the whole sentence in the input field you need javascript for this. In this post is very useful to archive this code. 


Code to set First letter capital in Input field:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Capitalizing first letter in a textbox</title>
<script type="text/javascript">
function capitalize(textboxid, str) {
// string with alteast one character
if (str && str.length >= 1)
{       
var firstChar = str.charAt(0);
var remainingStr = str.slice(1);
str = firstChar.toUpperCase() + remainingStr;
}
document.getElementById(textboxid).value = str;
}
</script>
<style>
.cs1{
border: 1px solid green;
height: 25px;
width: 400px;
padding:12px;
}
</style>
<body style="margin-top:60px; margin-left:40px;">
<form name="myform" method="post">
<input class="cs1" type="text" id="mytextbox" onkeyup="javascript:capitalize(this.id, this.value);" placeholder="Enter text here..">
</form>
</body>
</html>