简体   繁体   中英

Change background color of input text field using JavaScript

How do I change the background color of a input text field using java script? I want to insert it in a form validation function like this:

        function validateForm()
        {
        var x=document.forms["form1"]["username"].value;
        if (x==null || x=="")
          {
   document.forms["form1"]["username"].style.backgroundColor = Black
          }
        }

Also, is there a way to do form validation with php without creating two pages? WHat would you recommend? Using JavaScript or php for validating the user input of a form? I already have a php process form which checks whether the user supplied the correct details like the password etc.

Thank you for any help

You are taking the value of the text input. You need to refer to the control itself:

function validateForm()
{
    var ctrl = document.forms["form1"]["username"];
    var x=ctrl.value;
    if (x==null || x=="") {
       ctrl.style.backgroundColor = color;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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