这个javascript&有什么问题? HTML代码

时间:2012-12-04 21:00:59

标签: javascript html

我写了这个简短的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>

3 个答案:

答案 0 :(得分:2)

您需要做两件事:

  1. 在“选择框架”下,选择“no wrap(head)”而不是“onLoad”。
  2. <form id="enrollment">更改为<form name="enrollment">

答案 1 :(得分:1)

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

[编辑]如果您将onLoad更改为no wrap (head)

,则以下答案适用于jsFiddle

我把所有代码都带到了我的计算机上的HTML文件中,将javascript置于脑中,一旦我改变了它就运行了

document.enrollment.cost.value = 1221;

document.forms.enrollment.cost.value = 1221;

答案 2 :(得分: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>