我有以下代码。
<fieldset id="test">
<label><b>(2)</b> Open Sub-tasks</label>
<div class="table-holder">
<table class="table">
<thead>
<tr>
<th style="width:40%;">Location/Problem</th>
<th style="width:30%;">Assignment</th>
<th class="align-right" style="width:30%;">Due Date</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>Bathroom, Plumbing</td>
<td>Johnny Fixalot</td>
<td class="align-right">03/14/2017</td>
</tr>
</tbody>
</table>
<ul class="multi-list tabs">
<li class="width-50 sub_task_complete">
<a class="first">Mark Complete</a></li>
<li class="width-50 sub_task_complete">
<a class="last even">Delete</a></li>
</ul>
</div>
<br>
<div class="table-holder">
<table class="table">
<thead>
<tr>
<th style="width:40%;">Location/Problem</th>
<th style="width:30%;">Assignment</th>
<th class="align-right" style="width:30%;">Due Date</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>Bathroom, Plumbing</td>
<td>Johnny Fixalot</td>
<td class="align-right">03/14/2017</td>
</tr>
</tbody>
</table>
<ul class="multi-list tabs">
<li class="width-50 sub_task_complete">
<a class="first">Mark Complete</a></li>
<li class="width-50 sub_task_complete">
<a class="last even">Delete</a></li>
</ul>
</div>
<br>
<hr>
</fieldset>
根据此代码,它显示2个任务,分别带有Mark Complete和Delete选项。选择任何选项时,特定“li”将被选中。我正在尝试验证是否选择了任何选项并尝试显示错误消息。 我的试用代码是 -
$('ul.multi-list').each(function(){
if($('li.sub_task_complete.selected').length == 0){
$('fieldset#test').addClass('error');
$('fieldset#test .table-holder').after('<span class="oops">Please select an option for completing or deleting sub task.</span>');
}
});
显示消息4/5次。我想在每个表格持有者之后只显示一条消息,如果未选中。
注意:可以有多个具有ul.multi-list类的字段集,因此li的sub_task_complete类只是区别因素。
答案 0 :(得分:0)
啊,在你对我的第一个回答发表评论后,我得到你正在做的事情。在这种情况下,您要使用.closest。很确定这会做你想要的。
// Iterate through the lists individually
$('ul.multi-list').each(function(){
// Set the errors variable for this list to 0
var errors= 0;
// Iterate through the li's in this list
// Increment errors if any of the tasks are missing .selected
$(this).find('li').each(function(){
if(!$(this).hasClass("selected")){
errors++;
}
})
// Check if this list has 2 errors meaning neither
// li has .selected and add the error class and message to
//this list only
if( errors ==2 ) {
$(this).closest('.table-holder').addClass('error');
$(this).closest('.table-holder').after('<span class="oops">Please select an option for completing or deleting sub task.</span>');
}
});
答案 1 :(得分:0)
您可以使用内置的jQuery函数来实现您的目标,而不是遍历所有li选项:
if($('li').filter('.selected').length == 0)
{
e.preventDefault();
alert('please select atleast one option');
}