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

StackOverflow https://stackoverflow.com/questions/23650161

  •  22-07-2023
  •  | 
  •  

سؤال

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 مع الإسناد
لا تنتمي إلى StackOverflow
scroll top