How to highlight label associated with text box using jQuery

jQuery is really a great library to provide various effects with ease. In this post, I will show you how to highlight the label associated with a particular textbox when it receives focus and remove highlighting when focus goes out using jQuery.

Before moving ahead, It is important to know that there is a tag called "label" in HTML which defines a label for input element.

From W3 Schools websites

The <label> tag defines a label for an <input> element.

The <label> element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the <label> element, it toggles the control.

The for attribute of the <label> tag should be equal to the id attribute of the related element to
bind them together.

So basically the label tag looks like below. Where "txtFirstName" is id of input textbox.

//Code Starts
<label for="txtFirstName">First Name</label>
//Code Ends

So the complete HTML code looks like,

//Code Starts
<label for="txtFirstName">First Name</label>
<input type="text" id="txtFirstName" />
<br/>
<label for="txtLastName">Last Name</label>
<input type="text" id="txtLastName" />
<br/>
<label for="txtEmail">E-Mail Add</label>
<input type="text" id="txtEmail" />?
//Code Ends

And this is the CSS class that is used to highlight the textbox.

//Code Starts
.focus {
    background: Yellow;
    border-radius: 6px;
    border: 1px solid Green;
}
//Code Ends

And below jQuery code, will select all the input with type text and then associate focus and blur event with them. On focus event, it finds the associated label and then add/remove CSS class.

//Code Starts
$(document).ready(function() {
    $('input[type$="text"]').focus(function() {
        $("label[for='" + this.id + "']").addClass('focus');
    }).blur(function() {
        $("label[for='" + this.id + "']").removeClass('focus');
    });
});?
//Code Ends

See result below.


If you want to implement this highlighting effect for all your controls (not for textbox only) then just modify the selectors so that it associates with all the input controls.

//Code Starts
$(document).ready(function() {
    $('input').focus(function() {
        $("label[for='" + this.id + "']").addClass('focus');
    }).blur(function() {
        $("label[for='" + this.id + "']").removeClass('focus');
    });
});?
//Code Ends
See Complete Code

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...