Javascript验证似乎不起作用?有什么错误吗?

时间:2017-06-16 14:42:44

标签: javascript html

我试图将错误搜索3小时,但我不知道为什么它不起作用。任何人都可以帮我吗? :(当我开始按下sumbit按钮时,整个表单刷新。这就像返回true而不是返回false。我确实将我的javascript链接到我的html。我在结束body标签之前将链接放在底部。

    <script src="../Js/feedbackscript.js"></script> 

我的HTML:

 <div id="form-main">
 <div id="form-div">

<form method="POST" class="form" id="form1" name="Form" onsubmit="return validateForm()">

  <p class="name">
    <input name="name" type="text"   class="feedback-input" placeholder="Name" id="name" />
                    <div id="name_error" class="val_error"></div>
  </p>  
  <p class="email">
    <input name="email" class="feedback-input" type="text" id="email" placeholder="Email" />
                    <div id="email_error" class="val_error"></div>
  </p>  
  <p class="hpnum">
    <input name="hpnum" type="text" id="contactnum" class="feedback-input" placeholder="Contact Number"/>
                    <div id="contact_error" class="val_error"></div>     
 </p>  
  <p class="text">
    <textarea name="text" id="comment" class="feedback-input" placeholder="Comment"></textarea>
                    <div id="comment_error" class="val_error"></div>
  </p>

  <div class="submit">
    <input type="submit" value="SEND" id="button-blue"/>
    <div class="ease"></div>
  </div>

</form>
</div>
</div>

我的Javascript:

    // GETTING ALL INPUT TEXT FIELDS
var username = document.forms["Form"]["name"];
var email = document.forms["Form"]["email"];
var comment = document.forms["Form"]["comment"];
var contact = document.forms["Form"]["hpnum"];
// GETTING ALL ERROR OBJECTS
var name_error = document.getElementById("name_error");
var email_error = document.getElementById("email_error");
var comment_error = document.getElementById("comment_error");   
var contact_error = document.getElementById("contact_error");
        name_error.textContent = "Username is required";
function validateForm(){

    // VALIDATE USERNAME
    if(username.value == ""){
        name_error.textContent = "Username is required";
        username.style.border = "1px solid red";
        username.focus();
        return false;
    }
    // VALIDATE EMAIL
    else if(email.value == ""){
        email_error.textContent = "Email is required";
        email.style.border = "1px solid red";
        email.focus();
        return false;
    }
    else if(contact.value == ""){
        comment_error.textContent = "Comment is required";
        comment.style.border = "1px solid red";
        comment.focus();
        return false;
    }
    else if(comment.value == ""){
        comment_error.textContent = "Comment is required";
        comment.style.border = "1px solid red";
        comment.focus();
        return false;
    }
    else{
        alert("Thank You! For Your Feedback!");
    }
}

1 个答案:

答案 0 :(得分:1)

我看到的一个问题是:您的全局变量在加载时填充,而您的validateForm()函数稍后会触发,并且值可能已更改。但变量内容未更新。