当您关注label
字段时,我正在尝试向input
添加一个类。我正在使用带有Bootstrap 4的jQuery 1.12.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>
答案 0 :(得分:2)
您需要在输入字段中添加一个ID。 for
属性链接到输入的id
属性。
这是一个可行的示例:
$(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>