在我输入和textarea的值中插入错误消息后,我正在寻找有关清除输入和文本区域值的帮助。这是我的代码:
HTML
<form name="form" action="contact-handler.php" method="post" onsubmit="return contact();">
<input type="text" name="name" placeholder="Name:">
<input type="text" name="email" placeholder="E-mail:">
<select name="subject">
<option value="0">Categories</option>
<option value="1">Web Design</option>
<option value="2">Web Development</option>
<option value="3">Graphic Design</option>
<option value="4">Photography / Video</option>
<option value="5">Marketing</option>
</select>
<textarea name="message" placeholder="Message:"></textarea>
<input class="button" type="submit" value="Send">
</form>
JavaSript
function contact() {
var name = form.name.value;
var email = form.email.value;
var atPosition = email.indexOf("@");
var dotPosition = email.lastIndexOf(".");
var subject = form.subject.value;
var message = form.message.value;
var flag = 0;
// Name
if(name != "" && name.length > 2 && !/[\d]/.test(name)) {
flag++;
form.name.style.border="1px solid #CCC";
}
else{
form.name.style.border="1px solid #D73300";
form.name.value="Please enter a valid name";
}
// Email
if(email != "" && atPosition > 1 && dotPosition > atPosition + 2 && dotPosition + 2 <= email.length) {
flag++;
form.email.style.border="1px solid #CCC";
}
else{
form.email.style.border="1px solid #D73300";
form.email.value="Please enter a valid email";
}
// Subject
if(subject > 0) {
flag++;
form.subject.style.border="1px solid #CCC";
}
else{
form.subject.style.border="1px solid #D73300";
}
// Message
if(message != "" && message.length > 30) {
flag++;
form.message.style.border="1px solid #CCC";
}
else{
form.message.style.border="1px solid #D73300";
form.message.value="Please enter a valid message";
}
// Flag
if(flag == 4) {
return true;
}
else
{
return false;
}
}
答案 0 :(得分:1)
更改placeholder
属性的值,而不是输入值。并使用类来设置样式:
form.element.className = 'error';
form.element.setAttribute('placeholder', "Can I haz a value?");
(fiddle)
更好的方法是将required="required"
属性添加到表单元素中,然后您可以使用:invalid
伪类来设置它们的样式:
input:invalid, textarea:invalid{
border: ....
}
答案 1 :(得分:0)
Vanilla JS方式:
window.onload = function() {
var form = document.forms["form"];
var formElems = form.getElementsByTagName('input');
formElems.concat(form.getElementsByTagName('textarea'));
for(i=0; i<formElems.length; i++) {
formElems[i].onclick = function() {
if(this.style.borderColor == '#CCC') {
this.value = '';
}
}
}
};
将此项置于您的联系功能之上。