[英]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.