2010-11-17 32 views
1

我使用這個腳本來自動填充表單上我的日期字段:基本的Javascript問題 - 使用什麼觸發器?

function clearText(thefield){ 
if (thefield.defaultValue==thefield.value) 
thefield.value = "" 
} 

function zp(n){ 
return n<10?("0"+n):n; 
} 
function insertDate(t,format){ 
var now=new Date(); 
var DD=zp(now.getDate()); 
var MM=zp(now.getMonth()+1); 
var YYYY=now.getFullYear(); 
var YY=zp(now.getFullYear()%100); 
format=format.replace(/DD/,DD); 
format=format.replace(/MM/,MM); 
format=format.replace(/YYYY/,YYYY); 
format=format.replace(/YY/,YY); 
t.value=format; 
} 

然後使用這個觸發事件:

onfocus="insertDate(this,'DD/MM/YYYY')" 

我的問題(這可能是一個基本的! )是什麼,我應該使用自動填充字段時,頁面加載,而不是當我點擊該字段?

回答

1

不要使用onload然後,不需要等到所有的頁面必須完成加載。把你想要的<input>之後的腳本調用insertDate。例如:

<form name="theform"> 
<input type="text" name="thefield" value="fallback date from server-side"> 
<script type="text/javascript"> 
// able to reference field now 
insertDate(document.theform.thefield,'DD/MM/YYYY'); 
</script> 
+0

完美,謝謝 – 2010-11-18 08:48:13

1
window.onload = function() { 
//your code here 
} 
0

如果你想填充它在頁面加載時,您可以使用onload處理上<body>,像這樣:<body onload="foo();">

0

如果你是自動填充字段,我相信它是較少混淆給用戶,如果它是在頁面加載時填充而不是在字段獲得焦點時填充。