0
我目前使用的HTML代碼:移動事件處理程序,單獨的文件
<form onsubmit="return validateForm()" action="page.html" >
Name: <input type="text" id="name" /><br />
Email: <input type="text" id="email" /><br />
<input type="submit" value="Submit" />
</form>
但我想我的事件處理程序移動到我的單獨的JavaScript,到名爲啓動功能。我的JavaScript看起來像這樣:
function formValidator(){
var name = document.getElementById("name");
var email = document.getElementById("email");
if(isAlphabet(name, "Fill in name"))
{
if(emailValidator(email, "Fill in email"))
{
return true;
}
}
return false;
}
function isAlphabet(elem, helpMsg)
{
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp))
{
return true;
}
else
{
alert(helpMsg);
elem.focus();
return false;
}
}
function emailValidator(elem, helpMsg)
{
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp))
{
return true;
}
else
{
alert(helpMsg);
elem.focus();
return false;
}
}
function initiate {
// ..
}
window.onload = initiate;
到目前爲止,我只找到了如何編寫代碼來重定向到新的網頁,但它不檢查,這是一個有效的代碼。我用這個:
HTML
<form id="form">
Name: <input type="text" id="name" /><br />
Email: <input type="text" id="email" /><br />
<input type="submit" value="Submit" />
</form>
的Javascript
document.getElementById("form").action = "page.html";
但我無法弄清楚如何寫這樣既.action="page.html"
和return validateForm()
工作。
很好,謝謝! – Benji