2017-08-01 63 views
0

我有一个这样的号码输入:检查输入为空,如果没有,添加类的父DIV

<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> 

我从API得到一些数据,然后附加到这些输入(因此用户可以编辑)。

这工作正常。问题是,我想一个类添加到此:

<div class="fg-line"> 

这是很简单的,如果我只有其中的一个与一个输入,但因为我有多重,我需要一些方法来检查每个输入和如果不为空添加类fg-toggled使得行变成了:

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

如果我刚一个输入,我应该这样做:

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

但我不知道如何做到这一点不用写为每个班级(有30+)。有没有办法迭代这个莫名其妙?我试着检查.place-edit,但由于它是一个类,如果任何类的输入不为空,那么它们都会添加新类。

+0

是的,你可以通过选择'class'迭代。看到这个帮助https://stackoverflow.com/questions/4735342/jquery-to-loop-through-elements-with-the-same-class – tech2017

+0

@ tech2017是的,但我测试什么?我是否还需要先检查每个ID('place_name'等)?这是棘手的部分(无论如何。) – jonmrich

回答

2

通过每个输入简单的回路,并使用寻父.closest()。

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

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

}); 

Sample plunkr

0

你可以只通过.place-edit类,然后检查值和类添加到家长,这样的循环:

$('.place-edit').each(function(){ 
    if($(this).val() != '' || $(this).val() != $(this).defaultValue) { 
    $(this).parent().addClass('fg-toggle'); 
    } 
}) 
2

可以使用filter()

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

不知道什么“默认“应该是或如何声明。可以在一个数据属性进行设置,并添加||上述过滤条件

-1

试试这个..我假设它们都具有相同的类

if (('#place_name').value != '' || ('#place_name').value != ('#place_name').defaultValue) { 
    $('.fg-line').each(function(){ 
    $(this).addClass('fg-toggle') 
    }); 
} 
+0

这个问题是,我不想写这个35次,因为我有所有不同的ID('#place_name') – jonmrich

+0

如果你不想重复35次,可以得到类似于: $('。fg-line')。each(function(){if(this).find('input')。val()!=='') $(这个)。addClass('fg-toggle') }); 或相似 –

+0

您需要获取父类并获取父类的输入并应用条件判断是否为true继续添加类似于我写的 –

1

使用每个()和最近() 试试这个:

$(".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>

+0

这会将'fg-toggle'类添加到每个'fg-line' 'if'语句总是评估为'true',但我的输入是空的。 – jonmrich

+0

@jonmrich权利我更新了我的答案 –