I am writing a timecard app. The stipulatioin is all Hours fields can only be whole hours or half hour increments. For example, 1.0 is good, 1.5 is good, 1.2 is bad, 1.9 is bad.
I would like to have the field automatically change a value of 1.9 to a value of 2.0 (perhaps onKeyUp).
I would like to have the field automatically change a value of 3.2 to a value of 3.0.
In a nutshell - only allow whole and half hour values. Otherwise round up OR round down.
Thanks for any help you can provide. I am successfully using the Pengoworks plugin for calculations - absolutely priceless. If you think modifications can be made to it, plz let me know.
Enter hours <input type = "text" id = "hours" size = "5" maxlength = "5" onkeyup ="chk()">
<script type = "text/javascript">
function chk() {
var val = document.getElementById("hours").value;
val = val.replace(/[^0-9\.]/gi, ""); // strip all but digits and decimal point
var valsplit = val.split(".");
valsplit[0] = parseInt(valsplit[0]);
if (valsplit[1]) {
valsplit[1] = valsplit[1].replace(/(\d)(.)/, '$1'); // only one digit after decimal point
if (valsplit[1] >5) {
valsplit[1] = 0;
valsplit[0] = valsplit[0] +1;
}
if (valsplit[1] <5) {
valsplit[1] = 0;
}
}
var newval = valsplit.join(".");
if (isNaN(newval)) {newval = ""}
document.getElementById("hours").value = newval;
}
</script>
Quizmaster: Name something a bald man does not have to buy.
Contestant: A razor.
Last edited by Philip M; 11-12-2010 at 08:02 AM..
Reason: Improvement
(b) onkeyup is a bad solution in my never overly humble opinion. What about the person who uses MOUSE ONLY to copy/paste a value into a form field? You will never get an onkeyup event. I'm not fanatic about it, but I very, very seldom use onkeyup in stuff I do.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Last edited by Old Pedant; 11-11-2010 at 08:19 PM..
(b) onkeyup is a bad solution in my never overly humble opinion. What about the person who uses MOUSE ONLY to copy/paste a value into a form field? You will never get an onkeyup event. I'm not fanatic about it, but I very, very seldom use onkeyup in stuff I do.
Well, simply make it read
Enter hours <input type = "text" id = "hours" size = "5" maxlength = "5" onkeyup ="chk()" onchange = "chk()" >
Yep. And as I said, yours is pretty nice in the way it handles idiotic entries. I'd still not worry about onkeyup on my own pages, but for anybody who wants to use it, your code is great.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.