基本上我有这个表格。当我按下“发送消息”按钮时,如果有一个没有值的字段,该字段将返回一个红色的错误消息。但是当我按下重置时,它不会将值更改为黑色文本,并且文本保持红色..我该如何解决这个问题?
<form id="contact" action="" onsubmit="checkContactForm( this ); return false;">
<p>Fill in the form below to send me a message!</p>
<p>
<label for="firstname">First name:</label>
<input name="firstname" id="firstname" onfocus="resetField( this );" />
</p>
<p>
<label for="lastname">Last name:</label>
<input name="lastname" id="lastname" onfocus="resetField( this );" />
</p>
<p>
<label for="email">E-mail address:</label>
<input name="email" id="email" onfocus="resetField( this );" />
</p>
<p>
<label for="message">Your Message:</label>
<textarea name="message" id="message" onfocus="resetField( this );"></textarea>
</p>
<p>
<button type="submit">Send Message</button>
<button type="reset">Reset Form</button>
</p>
</form>
和这个javascript:
var requiredFields = [ "firstname", "lastname", "email", "message" ];
function checkContactForm( theForm ) {
for ( i in requiredFields ) {
var fieldName = requiredFields[ i ];
var theField = theForm[ fieldName ];
if ( !theField.value || theField.value == "Error" ) {
theField.style.color = "#f66";
theField.value = "Error";
var emptyFields = true;
}
}
if ( !emptyFields ) {
theForm.submit();
}
}
function resetField( theField ) {
if ( theField.value == "Error" ) {
theField.value = "";
theField.style.color = "#000";
}
}
答案 0 :(得分:1)
重置表单只会重置值,因此您需要向重置按钮添加一个侦听器以更改颜色,例如。
<input type="reset" onclick="resetForm(this);">
并且在函数中类似:
function resetForm(el) {
var form = el.form;
for (var els = form.elements, i=els.length; i; ) {
els[--i].style.color = #000000;
}
}
上面只是一个例子,你需要根据它来定制它。
此外,在数组中使用for..in并不是一个好主意。你在哪里:
for ( i in requiredFields ) {
你最好做一些事情:
var requiredFields = {'firstname':'', 'lastname':'', 'email':'', 'message':''};
var element, elements = form.elements;
for (var i=0, iLen=elements.length; i<iLen; i++) {
element = elements[i];
if (element in requiredFields) {
if (!element.value || element.value == 'Error') {
...
此外,如果表单控件具有名称,则它们也很少需要ID。