spacer
Yehuda Shiran November 30, 1999
Coloring Text Fields
Tips: November 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

The popular background-color CSS property is implemented in JavaScript as backgroundColor. The following syntax can be used to change the background color of an element:

object.style.backgroundColor = colorValue;

The value of colorValue can be any color value. The backgroundColor property is supported by Navigator 4 and Internet Explorer 4 (and above). However, it cannot be associated with form elements in Netscape Navigator. Therefore, our form validation script works with both browsers, but only colors the invalid text fields in Internet Explorer:

<SCRIPT LANGUAGE="JavaScript">
<!--

function setColor(el, bg) {
  if (el.style) el.style.backgroundColor = bg;
}

function checkInput(form) {
  var bgBad = "#cccc99";
  var bgGood = "white";
  var valid = true;
  if (form.first.value == "") {
    valid = false;
    setColor(form.first, bgBad);
  } else {
    setColor(form.first, bgGood);
  }
  if (form.last.value == "") {
    valid = false;
    setColor(form.last, bgBad);
  } else {
    setColor(form.last, bgGood);
  }
  if (!valid) alert("Please fill out the entire form.");
  return valid;
}

// -->
</SCRIPT>
<FORM onSubmit="return checkInput(this)">
First name: <INPUT TYPE="text" NAME="first" SIZE="30" VALUE=""><BR>
Last name: <INPUT TYPE="text" NAME="last" SIZE="30" VALUE=""><BR>
<INPUT TYPE="submit" VALUE="send">
</FORM>

If you're using Internet Explorer 4 (or above), give it a try:

First name:
Last name:

People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business