[英]Validate all the inputs of a table in jquery
我有一组动态生成的输入,它们的 id 根据数组中的项目数递增
<table width="100%">
<?php $i = 1; ?>
<?php foreach ($products as $product) { ?>
<tr>
<td>
<p><b><?php echo $product['name']; ?></b></p>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
<div class="form-group">
<label class="control-label" for="firstname_<?php echo $i; ?>">First Name:</label>
<input name="firstname_<?php echo $i; ?>" id="firstname_<?php echo $i; ?>" required>
</div>
</td>
<td>
<div class="form-group">
<label class="control-label" for="lastname_<?php echo $i; ?>">Last Name:</label>
<input name="lastname_<?php echo $i; ?>" id="lastname_<?php echo $i; ?>" required>
</div>
</td>
<td>
<div class="form-group">
<label class="control-label" for="recipient_number_<?php echo $i; ?>"> Phone Number:</label>
<input name="recipient_number_<?php echo $i; ?>" id="recipient_number_<?php echo $i; ?>" required>
</div>
</td>
<td>
<div class="form-group">
<label class="control-label" for="recipient_email_<?php echo $i; ?>"> Email:</label>
<input name="recipient_number_<?php echo $i; ?>" id="recipient_email_<?php echo $i; ?>" required>
</div>
</td>
</tr>
<?php $i++; ?>
<?php } ?>
</table>
我正在尝试寻找一种使用 JQuery 循环遍历所有生成的输入以确保它们不为空的方法
尝试使用它 - 您可以在此处用表 ID 替换table
- $('#tableId :input')
$('table :input').each(function(){
//Enter your code to validate input
console.log($(this).attr('name') + " : " + $(this).val());
});
试试这个片段。
这将允许您验证空字段,并尝试使用过滤器,这有助于您在没有任何循环的情况下完成此操作。
更多信息过滤器
$('#sender_container').on('submit',function(e) { e.preventDefault(); validate(); }); function validate() { $('#sender_container > input[type="text"]') .removeClass('error') .filter(function() { // Remove error classes. Filter return !$.trim(this.value); }) .addClass('error'); }
.error { border: 1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="post" id="sender_container"> <input type="text" name="name[]" /> <input type="text" name="name[]" /> <input type="text" name="name[]" /> <input type="text" name="name[]" /> <input type="text" name="name[]" /> <input type="submit" name="submit" /> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.