tags:

views:

53

answers:

2

The following is my code for changing the color of the label of the input field in focus:

    $(document).ready(function() {

var name = $(this).attr("name");

$(".comm-input").focus(function() {
 $("label[for=name]").css({"color" :"#669900"});
}); 

$(".comm-input").blur(function() {
 $("label[for=name]").css({"color" :"#999999"});
});  

});

.comm-input is the class of the input. Any ideas on why its not working?? Thanks!

A: 

You need to change your selector to this:

$(".comm-input").focus(function() {
     $("label[for=" + this.name + "]")).css("color", "#669900");
});

It won't automatically change the string literal "name" with the value of your name variable.

Also, when you were grabbing the name variable, this refers to the document, not to the element being focused.

TM
+3  A: 

You have a couple of issues.

Firstly, you're defining name in ready(). It won't have any (relevant) meaning there. The correct place to find that is inside your event handlers.

Secondly, you're not substituting the value of name, you're using the literal name. You want:

$(function() {
  $(".comm-input").focus(function() {
    $("label[for" + this.name + "]").css({"color" :"#669900"});
  }).blur(function() {
    $("label[for=" + this.name + "]").css({"color" :"#999999"});
  }); 
});

Lastly, I'd strongly suggest using a CSS class instead of directly setting CSS style attributes. They are problematic to remove. For example, what if the normal color is green? Your code will set it to something else it wasn't but removing a class will set it correctly so CSS:

label.highlight { color: #690; }

with:

$(function() {
  $(".comm-input").focus(function() {
    $("label[for" + this.name + "]").addClass("highlight");
  }).blur(function() {
    $("label[for=" + this.name + "]").removeClass("highlight");
  }); 
});
cletus
Awesome! Thanks!
WillyG