Search code examples
jqueryonbluronfocus

jQuery onfocus onblur problem


I'm having some trouble getting my onFocus and onBlur events to work properly

Here's what I got

var var1

$("input").focus(function() {

  var1 = $(this).val()

if ( $(this).val()==var1) {
       $(this).val('').css({'color': "#000", 'font-style': 'normal', 'font-weight': 'bold'});
   }  
    $(this).css({'background-color':'#d7df23' });    
});

$("input").blur(function() {
   if ( $(this).attr("value")=="") {
       $(this).val(var1).css({'color': "#666", 'font-style': 'italic', 'font-weight': 'normal'});
   }   
    $(this).css({'background-color':'#EEEEEE' });      
});

And here's my HTML

<input type="text" id="tbTitle" value="Title">

<input type="text" id="tbTitle1" value="Title1">

<input type="text" id="tbTitle2" value="Title2">

This works if you don't change the value of the textbox.

Basically I want to get the original value of the input and store it in a var and then if the field is blank put the original value back.

At the moment it is putting the value of whatever is in the textbox on focus

Is there a way to store the original value and only change it to that onBlur?

Here's a link to my jsfiddle


Solution

  • Here is my solution...

    http://jsfiddle.net/Sohnee/YTTD5/4/

    Or in code...

    var originalValues = new Array();
    
    $("input").focus(function() {
    
        if (!originalValues[this.id]) {
          originalValues[this.id] = $(this).val()
        }
    
        if ( $(this).val()==originalValues[this.id]) {
               $(this).val('').css({'color': "#000", 'font-style': 'normal', 'font-weight': 'bold'});
           }  
            $(this).css({'background-color':'#d7df23' });    
       });
    
        $("input").blur(function() {
           if ( $(this).attr("value")=="") {
               $(this).val(originalValues[this.id]).css({'color': "#666", 'font-style': 'italic', 'font-weight': 'normal'});
           }   
            $(this).css({'background-color':'#EEEEEE' });      
       });