I need to further simplify this 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;" onpaste="return false;" autocomplete="off" >
<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) {
var rE = /\D/g; // remove any characters that are not numbers
var originalGPA = document.getElementById(gPAElementID);
var originalGPAVal = originalGPA.value;
var gPAVal = originalGPA.value.replace(rE,"");
var gPAValFirstCharacter = gPAVal.charAt(0);
if ( ( ( parseFloat(originalGPAVal) ) > 4 ) && ( ( parseFloat(originalGPAVal) ) < 5 ) )
{
originalGPA.value = "4.00";
}
else
{
if ( ( gPAVal >= 0 ) && ( gPAValFirstCharacter < 5 ) )
{
gPALen = gPAVal.length;
if ( gPALen > 1 )
{
gPAa=gPAVal.slice(0,1);
gPAb=gPAVal.slice(1);
originalGPA.value = gPAa + "." + gPAb;
}
else if ( gPALen == 1 )
{
originalGPA.value = gPAVal + ".";
}
else
{
originalGPA.value = gPAVal;
};
}
else
{
originalGPA.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
1 Answer 1
I'd maybe try something like the following. What I've done is remove the string manipulation and concentrate on rounding the numbers.
function formatGPA(originalGPA) {
var originalGPAVal = originalGPA.value;
var gPAVal = parseFloat(originalGPAVal);
if (gPAVal < 0) {
gPAVal = 0;
} else if (gPAVal > 4) {
gPAVal = 4;
}
if (isNaN(gPAVal)) {
// Some kind of error handling
} else {
originalGPA.value = gPAVal.toFixed(2);
}
}
//<!-- When executed this script [ABOVE] auto-formats a Grade Point Average (GPA) field given the element ID [END] -->
document.getElementById('collegeGPA').onblur = function () {
formatGPA(this);
};
The only problem with this is it's difficult to manipulate it as one types. Therefore I've actioned the manipulation only on blur
.