atrum Posted March 17, 2009 Share Posted March 17, 2009 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. Quote Link to comment Share on other sites More sharing options...
Floydian Posted March 17, 2009 Share Posted March 17, 2009 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. Quote Link to comment Share on other sites More sharing options...
darkfreaks Posted March 17, 2009 Share Posted March 17, 2009 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'; } } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.