Jarla Jarla - 1 month ago 6
jQuery Question

How can I add a class to all form groups that have an empty input inside?

By click on my button "make pink" I want to highlight the input fields, that do not have any text inside:



$("#highlight").click(function () {
$('.form-group input').blur(function() {
if (!$(this).val()) {
$(this).parents('.form-group').addClass('has-error');
}
});
});

.has-error {
background-color: pink
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="form-group">
<label>Input</label>
<input type="text" id="input">
</div>

<div class="form-group">
<label>Input</label>
<input type="text" id="input" value="Some Text">
</div>

<button id="highlight">Make pink</button>





Not adding the class, and I do not know why

Answer

From what I understand, you want the inputs to turn pink as soon as you click the button. However, you have a blur event nested inside your click event. Meaning that once you click the button, it then binds the blur event to the inputs and waits for that to happen. So if you click the button then click one of your inputs and click away, it will turn pink.

To get it to happen immediately on click, get rid of that blur event and change it to something like this, which is using jQuery's each function:

$("#highlight").click(function () {
  $('.form-group input').each(function() {
   if (!$(this).val()) {
     $(this).parents('.form-group').addClass('has-error');
   }
  });
});