在javascript验证成功时隐藏span元素

时间:2014-04-15 02:44:05

标签: javascript html

我坚持在JavaScript验证成功时如何使span元素再次隐藏。目前onchangeonblur出现红色范围,如果没有文字或名称字段中有数字,则显示错误。当输入正确的文本时,这不会消失。我只是想知道如何在输入正确的文本时使此消息消失?代码如下。

JavaScript的:

function validateName() {
    var name = form.firstname.value; 
    if (form.firstname.value == "") { 
        document.getElementById("firstnameInvalid").style.visibility = "visible";  
        return false;
    } if (/[0-9]/.test(name)) {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
        return false;  
    } 
    return true;
}

表单HTML:

<form name="form" method="post" action= "userdetails.html" onsubmit="return validate(this)">

<p>First Name:<input type="text" name="firstname" onblur="validateName()" onchange="validateName()" id="name">
    <span id="firstnameInvalid" style="color:red; visibility:hidden"> First Name is Invalid </span>
</p>

2 个答案:

答案 0 :(得分:8)

你走在正确的轨道上。

http://jsfiddle.net/isherwood/BHe5Z/

function validateName() {
    var name = form.firstname.value;

    if (form.firstname.value == "") {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
        return false;
    } else if (/[0-9]/.test(name)) {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
        return false;
    } else {
        document.getElementById("firstnameInvalid").style.visibility = "hidden";
    }
}

您可以使用变量并删除返回来简化此操作,这似乎是不必要的:

http://jsfiddle.net/isherwood/BHe5Z/1/

function validateName() {
    var name = form.firstname.value;

    if (name == "") {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
    } else if (/[0-9]/.test(name)) {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
    } else {
        document.getElementById("firstnameInvalid").style.visibility = "hidden";
    }
}

答案 1 :(得分:6)

我建议您使用:

style="display:none" - 隐藏的 style="display:block" - 可见

HTML:

<p>First Name:<input type="text" name="firstname" onblur="validateName(this.value)"     onchange="validateName(this.value)" id="name">
      <span id="firstnameInvalid" style="color:red; display:none;"> First Name is Invalid </span></p>

使用Javascript:

function validateName(name) {

   if (name == "")
   { 
       document.getElementById("firstnameInvalid").style.display="block";
       return false;
   }
   else if (/[0-9]/.test(name))
   {
       document.getElementById("firstnameInvalid").style.display = "none";
       return false;  
   }
   return true;
}