Jump to content

onBlur and onFocus Form Validation Problems


atrum

Recommended Posts

Ok, so still very newbish at javascript, so naturally I have an issue thats causes headaches.

 

What I need to have a fields' background turn red if the field is blank onblur() or turn white onfocus().

So far, I am unable to get any change to occur.

 

My code is below.

 

 

<td class="info">
<input id="txt_fristname" name="txt_firstname" type="text" onfocus="onSelect()" onblur="onUnSelect()"/>
</td>

 

function onUnSelect()
{
var input = document.getElementById('txt_firstname');
if(input.value == '')
{
	input.style.background = 'red';
}
else
{
	input.style.background = '';
}
}


function onSelect()
{
var input = document.getElementById('txt_firstname');
if (input.focus = true)
	{
	input.style.background = 'white';
	}
}

 

 

Any help you can provide would be appreciated.

The first thing to do is use an alert() function in each of those methods to confirm they are being called.

 

Secondly, style.background should probably be changed to style.backgroundColor since you're just setting the background color and not all of the background properties.

 

Third, I've found far better cross browser functionality by using the hex numbers instead of color names.

 

Forth, the code if (input.focus = true) has a = instead of a == or  ===.

 

Fifth, I suspect that using element.focus might not have good cross browser support. I could be wrong, but why not just eliminate the if block since your blur function will cancel anything the focus function does, since it will be called after the focus. I presume you are concerned about the focus function being called and the user quickly clicking over to something else before the focus function finishes. Which, while that can happen, the blur function will correct that for you.

Fixed:

function onUnSelect()
{
   var input = document.getElementById('txt_firstname');
   if(input.value === '')
   {
      input.style.background = 'red';
   }
   else
   {
      input.style.background = '';
   }
}


function onSelect()
{
var input = document.getElementById('txt_firstname');
if (input.focus === true)
      {
      input.style.background = 'white';
      }
   }

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.