Tural Ali
Tural Ali

Reputation: 23290

jQuery taking control over label's border color

My jQuery function looks like that

$('input[type="text"]').focus(function() {  
       $("label").css("border-bottom-color", "red");
    });  
    $('input[type="text"]').blur(function() {  
       $("label").css("border-bottom-color", "#e6e6e6");
    });  

1) I have a bunch of text inputs in my form. What I want to do is to change bottom border color of focused text boxes label (there is one label for every text box. And I want to change only focused text boxes label's border color). But my functions changes all labels' border colors at once. How to fix that problem?

2) I have 2 forms. with id's form1 and form2. I want to do same things to second form but color will be another. How to modify this func?

My forms are looking like that

<form id="form1">
 ...
<label for="fname">First Name</label>
<input name="fname" placeholder="please enter your first name" type="text" /> 
 ...
</form>

<form id="form2">
 ...
<label for="job">Your Job</label>
 ...
<input name="job" placeholder="please enter your job" type="text" />
</form>

Upvotes: 0

Views: 1555

Answers (4)

David Thomas
David Thomas

Reputation: 253456

Use both CSS and JavaScript:

$('input:text, input:password, textarea').focus(
    function(){
        $(this).prev('label').addClass('focused');
    }).blur(
    function(){
        $(this).prev('label').removeClass('focused');
    });

And, in the CSS:

#form1 label.focused {
    border-bottom: 1px solid red;
}

#form2 label.focused {
    border-bottom: 1px solid green;
}

JS Fiddle demo.

Upvotes: 1

biziclop
biziclop

Reputation: 14616

How about this fiddle?

http://jsfiddle.net/RvYca/3/

label tag's for attribute references to an input's id attribute, not its name. I moved the styles to css too.

Upvotes: 1

danpickett
danpickett

Reputation: 2046

your selector is not specific enough for manipulating the css. You must be specific about which label you want to update. Something like this:

$('input[type="text"],textarea,input[type="password"]').focus(function() {  
   $("label[for='" + $(this).attr('id') + "']").css("border-bottom-color", "red");
}); 

Upvotes: 0

dnuttle
dnuttle

Reputation: 3830

For question 1, use $(this) as your selector:

$('input[type="text"]').focus(function() {  
   $(this).css("border-bottom-color", "red");
});  
$('input[type="text"]').blur(function() {  
   $(this).css("border-bottom-color", "#e6e6e6");
});

For question 2, do you mean, after the user has selected both items, in either order? They can't both be in focus at the same time.

Upvotes: 0

Related Questions