Check if input is empty, if not, add class to parent div

I have a number of inputs like this:

<div class="fg-line">
    <input type="text" class="form-control fg-input place-edit placeInformation" id="place_name">
    <label class="fg-label">Place Name</label>
</div>
<div class="fg-line">
    <input type="text" class="form-control fg-input place-edit placeInformation" id="place_address">
    <label class="fg-label">Place Address</label>
</div>

I get some data from an API and then append to these inputs (so the user can edit).

This works fine. The issue is that I want to add a class to this:

<div class="fg-line">

This is simple enough if I only have one of these and one input, but since I have multiple, I need some way to check each input and if not empty add the class fg-toggled such that the line becomes:

<div class="fg-line fg-toggled">

If I had just one input, I'd do this:

if (('#place_name').value != '' || ('#place_name').value != ('#place_name').defaultValue) {
  $('.fg-line').addClass('fg-toggle')
}

But I don't know how to do this without writing this out for every class (there are 30+). Is there a way to iterate this somehow? I tried checking .place-edit but since it's a class, if any of the inputs with the class are not empty then they all get the new class added.


Simply loop through each input and find the parent using .closest().

$('.placeInformation').each(function() {
    var $input = $(this);

    if ($input.val()) {
        var $parent = $input.closest('.fg-line');
        $parent.addClass('fg-toggled')
    }

});

Sample plunkr


Can use filter()

$('.fg-line').has('.placeInformation').filter(function(){
   return !$(this).find('.placeInformation').val()
}).addClass('fg-toggled')

Not sure what "default" should be or how it is declared. Could be set in a data attribute and add an || to above filter condition


使用each()和nearest()试试这个:

$(".fg-input").each(function() {

  if ($(this).val() != '') {
    $(this).closest(".fg-line").addClass('fg-toggle');
  }
})
.fg-toggle
{
color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fg-line">
  <input type="text" class="form-control fg-input place-edit placeInformation" id="place_name">
  <label class="fg-label">Place Name</label>
</div>
<div class="fg-line">
  <input type="text" class="form-control fg-input place-edit placeInformation" id="place_address">
  <label class="fg-label">Place Address</label>
</div>
链接地址: http://www.djcxy.com/p/83522.html

上一篇: 无法使用jQuery .each循环使类中的单个div可拖动

下一篇: 检查输入是否为空,如果不是,则将类添加到父div