2012-12-04 129 views
-5

我已經寫了這個簡短的html和javascript代碼。您可以訪問代碼http://jsfiddle.net/a4Mz5/8/,但它似乎沒有工作。我正在尋找價值點擊提交填充。此javascript&html代碼有什麼問題

<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> 
+7

正好不工作怎麼辦?你在期待什麼? –

回答

2

有你需要做兩件事情:

  1. 在「選擇框架」,挑選,而不是「無包(頭)」「的onLoad」。
  2. 變化<form id="enrollment"><form name="enrollment">
1

我不能讓它在jsFiddle中工作。它一直顯示出ReferenceError: updateCost is not defined的錯誤。

[編輯]下面的回答工作中的jsfiddle如果更改onLoadno wrap (head)

我把所有的代碼爲HTML文件在我的電腦上,放置在JavaScript中的頭,和它的工作,一旦我改變

document.enrollment.cost.value = 1221; 

document.forms.enrollment.cost.value = 1221; 
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>