简体   繁体   English

Javascript-验证表单(如果发现错误)将表单字段背景颜色更改为红色

[英]Javascript - Validate form if error found change form field background color to red

Ive got a form, when the user clicks on a field the value clears, when the user clicks submit, AND an error is found the background color of the field should change to red. 我有一个表格,当用户单击字段时,值将清除,当用户单击提交时,并且发现错误,该字段的背景色应更改为红色。

My problem 我的问题

I manage to clear the value of the field when a user clicks it, and I managed to change the color of the field to red when an error is found, BUT when the error is found when the user clicks submit the background color only change to red for a split second and then the field value reapers again. 当用户单击时,我设法清除了该字段的值,并且当发现错误时,我设法将该字段的颜色更改为红色,但是当用户单击时,当发现错误时,该字段的颜色提交仅将背景色更改为红色持续一秒钟,然后字段值再次增加。 Ive been battling away with this for the whole morning any help would be appreciated, code follows: 我整天都在努力解决这个问题,我们将不胜感激,代码如下:

function validate(){
    //form validation
    var name=document.getElementById('name');
     if (name.value == null || name.value==""){
       name.style.backgroundColor="red";
     }  

<form id="enquire" method="post">
    <h2>Test Drive an Audi Today</h2>
    <input type="text"  value="Name" class="textbox" id="name" name="name" onclick="if(this.value=='Name') this.value='';" /><br />


<input type="submit" name="submit" class="butt" value="Send" onclick="validate()"  />
       <span class="buttonText">We'll Call you Back!</span>
    </form>

Change 更改

<input type="submit" name="submit" class="butt" value="Send" onclick="validate()"  />
       <span class="buttonText">We'll Call you Back!</span>

to

<input type="submit" name="submit" class="butt" value="Send" onclick="return validate()"  />
       <span class="buttonText">We'll Call you Back!</span>

The closing bracket of the function is missing. 该函数的右括号缺失。

function validate(){
    //form validation
    var name=document.getElementById('name');
     if (name.value == null || name.value==""){
       name.style.backgroundColor="red";
       return false;    // add this line
     }
}   // This was missing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM