views:

237

answers:

3

I'd like to make the background image for my input field disappear once the user has typed any amount of text in it. Is there a simple way to do that in javascript? I can get it so the bg disappears while the field is focused, but then it returns once they move on to the next field.

HTML:
Call me at <input name="phone" type="text" class="phone-field" id="phone">
CSS:

.form input {
  background-color:transparent;
}
.form input:focus {
  background-color:#edc;
  background-image:none;
}
input.phone-field {
  background-image: (url/images/phonebg.png);
  background-repeat: no-repeat;
  background-position: left 1px;
}
+1  A: 

with jquery, you could do something like

 $('#phone').focus(function(){
     var text = $(this).val();   
     if(text != ''){
        $(this).css('background-image', 'none');       
     }
 });
brian_d
+1  A: 
$("#inputId").focus(function() {
   if ($(this).value != "") {
     $(this).css("background-image", "none");
   }
}).blur(function() {
   if ($(this).value == "") {
      $(this).css("background-image", "url(/images/phonebg.png)");
   }
});
GerManson
fixed simple typo... but looking at it, you also mean either `$(this).val()`, or `this.value`, but there's not a `$(this).value`. Also surely this won't remove the background when you type, until you blur? How about always removing the background onfocus, but only putting the background back if empty on blur.
bobince
+1  A: 

Or for maximum browser compatibility (ahem, IE):

$("input.phone-field").change(function() { $.trim($(this).val()) != "" ? $(this).toggleClass("bg", false) : $(this).toggleClass("bg"); });

And the markup:

<input type="text" class="phone-field bg" />

Just add the background image CSS code to the ".phone-field.bg" selector.

This would remove the background as soon as some text is entered (and bring it back if no text is entered).

subkamran
So where do I put the java? *confused* I don't really understand as much about javascript as I thought I did.
aslum