...

View Full Version : cents in text input



fael097
07-14-2010, 03:16 PM
hi folks, i needed a text input so the user that will register a product, will make sure to enter the cents, and not just the raw money, making it to be stored incorrectly on my database.

for example, if i type "1" the output inside the text field will be automatically "0.01", so the user HAS to type the cents.

thanks in advance

tomws
07-14-2010, 04:52 PM
What's your question?

fael097
07-14-2010, 05:03 PM
well my question is how to make it... how to program a javascript function that updates the typed value to cents on key down. again, if i type 1, it will display 0.01 on the text field, if i type 100, it will display 1.00
thanks in advance

fael097
07-14-2010, 05:03 PM
well my question is how to make it... how to program a javascript function that updates the typed value to cents on key down. again, if i type 1, it will display 0.01 on the text field, if i type 100, it will display 1.00
thanks in advance

mrhoo
07-14-2010, 05:04 PM
who.value= (who.value/100).toFixed(2);

<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title> dollars and cents</title>
<script>

function formatCents(e){
var who, val;
e= window.event || e;
who= e.srcElement || e.target;
if(who){
val= who.value.replace(/\D+/g,'');
if(isNaN(+val)){
who.value= '0.00';
who.select();
}
else who.value= (val/100).toFixed(2);
if(e.stopPropagation) e.stopPropagation();
e.cancelBubble= true;
}
}
onload= function(){
var who= document.getElementsByName('dollarcents')[0], F= who.form;
F.onsubmit= function(){alert(parseFloat(who.value).toFixed(2))}
who.onkeyup=formatCents;
who.select();
}
</script>
</head>

<body>
<form action= "" method= "post">
<fieldset>
<label style= "text-align:right;font-size:x-large"> Enter amount: $

<input size= "11" name= "dollarcents" type= "text" value= "0.00"
maxLength="11" style= "text-align:left;font-size:x-large">
</label>
</fieldset>
</form>
</body>
</html>

fael097
07-14-2010, 05:53 PM
thanks, thats what i need, and it works!

just some thoughts:
-onkeydown would be perfect, but changing it, will return 3 digits after the decimal, since it updates after the next key down, and that might add another digit, and that way, it will always have 3 decimals
-if i type a number in front of it, it will simply add to the existing 0.00 so if i type number 1 AFTER the 0.00 it will work, but if i type 1 before, it will be 10.00, and i wanted to add digits to the first decimal regardless of where i type.

is that possible?

mrhoo
07-14-2010, 06:02 PM
The input value does not change at onkeydown, it changes onkeyup.

fael097
07-14-2010, 06:08 PM
i know, but changing on key up gives me unwanted delay, thats why i asked for on key down



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum