AmanSahota
AmanSahota

Reputation: 33

Focus on label elements not working with Bootstrap 4

I am trying to add a class to the label when you focus on the input field. I am using jQuery 1.12.4, with Bootstrap 4.

$(function() {
  $('form :input').focus(function() {
    $('label[for="' + this.id + '"]').addClass('labelfocus');
  }).blur(function() {
    $('label[for="' + this.id + '"]').removeClass('labelfocus');
  })
});
.labelfocus { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form class="needs-validation" novalidate>
  <div class="form-group row">
    <div class="col-md-7">
      <label for="firstName">* First Name</label>
      <div class="input-group">
        <input type="text" name="firstName" class="form-control" required>
        <div class="valid-feedback">Great! You've done it.</div>
        <div class="invalid-feedback">Please add your first name.</div>
      </div>
    </div>
  </div>
</form>

Upvotes: 0

Views: 667

Answers (1)

user9019817
user9019817

Reputation:

You need to add an ID to the input field. The for attribute links to the id attribute of an input.

Here's a working example:

$(function () {
    $('form :input').focus(function() {
        $('label[for="' + this.id + '"]').addClass('labelfocus');
    })
    .blur(function() {
        $('label[for="' + this.id + '"]').removeClass('labelfocus');
    })
});
.labelfocus {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form class="needs-validation" novalidate>
<div class="form-group row">
    <div class="col-md-7">
        <label for="firstName">* First Name</label>
        <div class="input-group">
            <input type="text" name="firstName" id="firstName" class="form-control" required>
            <div class="valid-feedback">Great! You've done it.</div>
            <div class="invalid-feedback">Please add your first name.</div>
        </div>
    </div>
</div>

Upvotes: 2

Related Questions