Simon S.
Simon S.

Reputation: 25

Remove class of a label when the corresponding input field has is filled in

I would like to remove the class "visuallyhidden" on labels of the text fields that have been filled in. So when I start typing something in an input field, I want the class "visuallyhidden" cleared so the label appears above the input field. However, when I erase the text from that input field, I want the class "visuallyhidden" to be added back to the corresponding label.

<label for="firstname" class="visuallyhidden">First Name</label>
<input type="text" id="firstname" placeholder="First Name"/>

<label for="lastname"  class="visuallyhidden">Last Name</label> 
<input type="text" id="lastname"  placeholder="Last Name"/>

My failed attempt at jQuery, which somewhat works, but affects all labels

$('input').keypress(function() {
    $('label').addClass('visuallyhidden');
});
$('input').blur(function() {
    if( !$(this).val() ) {
        $('label').removeClass('visuallyhidden');
    }
});

Upvotes: 1

Views: 1507

Answers (2)

T J
T J

Reputation: 43156

You can use jQuery toggleClass() method as follows:

$(":input").on("keyup", function() {
  $(this).prev("label").toggleClass("visuallyhidden", (this.value==""))
});
.visuallyhidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="firstname" class="visuallyhidden">First Name</label>
<input type="text" id="firstname" placeholder="First Name" />

<label for="lastname" class="visuallyhidden">Last Name</label>
<input type="text" id="lastname" placeholder="Last Name" />

Upvotes: 1

Sparky
Sparky

Reputation: 98718

To target the specific label, you simply need to traverse the DOM with jQuery methods...

$('input').keypress(function() {
    $(this).prev('label').addClass('visuallyhidden');
});
$('input').blur(function() {
    if( !$(this).val() ) {
        $(this).prev('label').removeClass('visuallyhidden');
    }
});

See: jQuery .prev()

$(this).prev('label') grabs the immediate preceding sibling of $(this) that matches the 'label' selector.

Upvotes: 1

Related Questions