I'm looking for a more cleaner and simpler solution to auto-format a text-box field intended only for the user to enter their college Grade Point Average (GPA). Here is my code:
<label for="collegeGPA">GPA:</label>
<input type="text" name="collegeGPA" id="collegeGPA" maxlength="4" style="width:45px;">
<script type="text/javascript">
//<!-- When executed this script [BELOW] auto-formats a Grade Point Average (GPA) field given the element ID [BEGIN] -->
function FormatGPA(gPAElementID) {
re = /\D/g; // remove any characters that are not numbers
gPAVal = document.getElementById(gPAElementID).value.replace(re,"");
gPAValFirstCharacter = gPAVal.charAt(0);
if ( ( gPAVal >= 0 ) && ( gPAValFirstCharacter < 5 ) )
{
gPALen = gPAVal.length;
if( gPALen > 1)
{
gPAa=gPAVal.slice(0,1);
gPAb=gPAVal.slice(1);
document.getElementById(gPAElementID).value = gPAa + "." + gPAb;
}
else
{
document.getElementById(gPAElementID).value=gPAVal;
};
}
else
{
document.getElementById(gPAElementID).value="";
};
};
//<!-- When executed this script [ABOVE] auto-formats a Grade Point Average (GPA) field given the element ID [END] -->
document.getElementById('collegeGPA').onblur = function (e) { FormatGPA(this.id); };
document.getElementById('collegeGPA').onfocus = function (e) { FormatGPA(this.id); };
document.getElementById('collegeGPA').onkeypress = function (e) { FormatGPA(this.id); };
document.getElementById('collegeGPA').oninput = function (e) { FormatGPA(this.id); };
document.getElementById('collegeGPA').onchange = function (e) { FormatGPA(this.id); };
</script>
...and here is my JSFiddle: http://jsfiddle.net/JamesAndersonJr/kxaBJ/1/ I'm looking for a simpler way to format the GPA input dynamically (i.e. as the user types it in). The format should be:
1st Character: any digit 0-4
2nd Character: Always a Period (should also be auto-inserted after user types a valid first digit)
3rd Character: any digit
4th Character: any digit
UPDATE: Lowest possible GPA is 0.00, not 1.00.