By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,985 Members | 2,920 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,985 IT Pros & Developers. It's quick & easy.

Changing field background colors in a form

P: 2
I'd like to change the background color in fields on a form when the user has made an entry in them. I'm having trouble figuring out the correct way to refer to the background color of the elements that I want. I'm checking to see if the field has any content. If not, I want the background color of that field to be yellow; if it is filled in, then I want it to turn white. Here's my function:

function changeColor(field) {
if (document.form1.field.length==0) {
document.form1.field.style.backgroundColor="yellow ";
} else {
document.reg.field.style.backgroundColor="white";
}
}

where form1 is the name of the form. I'm using an onblur() event handler in the fields where I want to use this function, with "this" as the value for the field parameter, like this:

<input name="fname" id="fname" onblur="changeColor(this)" />

Any ideas what I'm doing wrong?
Apr 27 '07 #1
Share this Question
Share on Google+
2 Replies


iam_clint
Expert 100+
P: 1,208
Expand|Select|Wrap|Line Numbers
  1. function changeColor(field) {
  2. var fv = field.value;
  3. if (fv.length==0) {
  4. field.style.background="yellow";
  5. } else {
  6. field.style.background="white";
  7. }
  8. }
  9.  
this should do ya.
Apr 28 '07 #2

pbmods
Expert 5K+
P: 5,821
Expand|Select|Wrap|Line Numbers
  1. <input type="text" onkeyup="validate(this);" ruleset="1" />
  2.  
  3. <script type="text/javascript">
  4.     function validate($element) {
  5.         $element.style.backgroundColor = (($element.value.length < $element.getAttribute('ruleset'))
  6.             ? 'yellow'
  7.             : 'white
  8.         );
  9.     }
  10. </script>
  11.  
Or if you use Prototype:

Expand|Select|Wrap|Line Numbers
  1.     if($element.value.length < $element.getAttribute('ruleset'))
  2.         $($element).addClassName('invalid');
  3.     else
  4.         $($element).removeClassName('invalid');
  5.  
Apr 28 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.