-5

我写了这个简短的 html 和 javascript 代码。您可以在http://jsfiddle.net/a4Mz5/8/访问代码,但它似乎不起作用。我正在寻找单击提交时要填充的值。

<html>
<head> Simple page </head>
<body>    
    <form id="enrollment">
        <input type="button" value="submit" onclick="updateCost();">

        value = <input type="text" name="cost">
    </form>    

<script>
function updateCost(){
    document.enrollment.cost.value = formatCurrency(0.9946153813);
}
function formatCurrency(num) {
    if(isNaN(num)) return "$0.00";
    // ACCOUNTING RULES: ROUND DOWN IF LAST DIGIT IS 5 AND SECOND TO LAST DIGIT IS EVEN
    num = new String(parseFloat(num).toFixed(3));
    if(num.charAt(num.length-1) == '5' && parseInt(num.charAt(num.length-2)) % 2 == 0) {
    num = num.substring(0,num.length-1);
    }   
    var cents = Math.abs(Math.round((num * 100) % 100));
    if(cents < 10) {
        cents = "0" + cents;
    }    
    var n = ""; var count = 0; var neg = num < 0;
    num = Math.floor(Math.abs(num)).toString();
    for(var i = num.length - 1; i >= 0; i--) {
        if(count > 0 && count % 3 == 0) n = "," + n;
        n = num.charAt(i) + n;
        count++;
    }    
    return (neg ? "-" : "") + ("$" + n + "." + cents);
}
</script>
</body></html>
4

3 回答 3

2

您需要做两件事:

  1. 在“Choose Framework”下,选择“no wrap (head)”而不是“onLoad”。
  2. 更改<form id="enrollment"><form name="enrollment">
于 2012-12-04T21:14:53.327 回答
1

我不能让它在 jsFiddle 中工作。一直显示错误ReferenceError: updateCost is not defined

onLoad[编辑] 如果您更改为,以下答案在 jsFiddle中有效no wrap (head)

我把所有代码都放到了我电脑上的一个 HTML 文件中,把 javascript 放在了头部,一旦我改变它就可以工作了

document.enrollment.cost.value = 1221;

document.forms.enrollment.cost.value = 1221;
于 2012-12-04T21:09:44.843 回答
1

试试这个:

    <html>
    <head> 
    <title>Simple page</title>
    <script type='text/javascript'>
         function updateCost(){
            document.getElementsByName('cost')[0].value = 1221;
         }
     </script> 
    </head>
    <body>    
        <form id="enrollment">
            <input type="button" value="submit" onclick="updateCost();">

            value = <input type="text" name="cost">
        </form> 
于 2012-12-04T21:13:02.680 回答