-3
我有下面的HTML表單,並且Javascript用於驗證HTML表單,所以在文本字段下面有一個隱藏的P元素來顯示它上面的字段中是否有任何錯誤, (fn文本字段)上設置的基於事件名稱(ID = fn)字段中的輸入觸發並隱藏P(ID = fnp)元素的鍵盤事件此代碼工作正常,但我希望它是動態的,這樣我就不會必須一次又一次爲每個文本字段編寫相同的代碼,我想調用norml函數並將參數傳遞到norml函數(元素名稱),以便它可以對每個文本字段執行相同的操作,但此方法不是工作:任何人都想引導我,我在這裏做錯了什麼。作爲參數傳遞給函數Javascript
這就是我想要做這不工作:
document.getElementById("fn").onkeyup = norml(pass an element name);
function norml(value received)
document.getelementbyID(received element ID name).color = red;
例:
function norml(dx, dxx) // receives a value as argument that is an element ID
{
dx.style.borderColor = '#d6d6d6';
dx.style.color = '#000000';
dxx.style.innerHTML = '';
dxx.style.visibility = 'hidden';
}
這就是工作,但將不得不做了每個文本字段分別
function norml()
{
document.getElementById("fn").style.borderColor = '#FF0000';
document.getElementById("fn").style.color = '#FF0000';
document.getElementById("fnp").style.borderColor = '#FF0000';
document.getElementById("fnp").style.innerHTML = '';
document.getElementById("fnp").style.visibility = 'hidden';
}
function validate() {
var errmsg = "";
var result = true;
var fname = document.getElementById("fn").value;
if (!fname.match(/^[a-zA-Z]+$/))
{
document.getElementById("fn").style.borderColor = '#FF0000';
document.getElementById("fn").style.color = '#FF0000';
document.getElementById("fnp").style.backgroundColor = 'lightpink';
document.getElementById("fnp").style.visibility = 'visible';
document.getElementById("fnp").innerHTML = "Please enter first name in alphabets";
document.getElementById("fn").onkeyup = norml;
return false;
}
if (errmsg != ""){ //only display message box if there is something to show
alert(errmsg);
}
}
function init()
{
var formData = document.getElementById("enqForm");
formData.onsubmit = validate;
}
window.onload = init;
<!DOCTYPE html>
<html lang="en">
<head>
<script src="scripts.js"></script>
<title></title>
</head>
<body id="enquire">
<section id="form">
<div>
<form id="enqForm" method="post">
<div class="formobj">
<div id="enquiry"><h1></h1></div>
<input id="fn" type="text" name="firstname" placeholder="First Name *" />
<input id="ln" type="text" name="lastname" placeholder="Last Name *" />
<p id="fnp" type="hidden"></p>
<p id="lnp" type="hidden"></p>
<input id="sendbutton" type="submit" value="Enquire" />
</div>
</form>
</div>
</section>
</body>
</html>
謝謝..
爵士的代碼是不完整的,它只是測試代碼和我是一個初學者...但由於任何方式... – TryllZ