[英]Validating dynamically created input elements
我有一個帶有動態創建的輸入元素的表單
<input type='button' value='Add Another Product' id='aprod'>
<table id='page3_inside'>
<tr id='ln1'>
<td>
<label for="product_cat">Product Category</label><br>
<input type='text' class="input product_category" name="product_category[]" style="font-family:verdana; width:150px; border: 1px solid #000000;">
</td>
<td>
<label for="qty">Qty</label><br>
<input type="text" value="" class="input qty" style="width:100px;" name="qty[]" placeholder="Qty" onkeypress="return isNumberKey(event)"/>
</td>
<td>
<label for="unit">Unit</label><br>
<input type='text' class="input unit" style="width:100px;" name="unit[]">
</td>
<td>
<label for="brand">PO Number</label><br>
<input type="text" value="" class="input po" name="po[]" placeholder="PO Number" style='width:150px; height:28px;'/>
</td>
</tr>
</table>
jQuery用於附加元素:
<script>
$('#aprod').on('click', function() {
$('#ln1').clone().appendTo('#page3_inside');
prodnum = prodnum + 1;
$('#conf_prodnum').val(prodnum);
});
</script>
由於所有字段都屬於一個類,因此如何驗證每個輸入。 在示例中,我使用ID作為選擇器,但是如何用class代替呢?
謝謝。
嘗試這樣的循環:
$('form').submit(function() {
$('form input.input').each(function() {
var valid = 1;
if ($(this).val() == '') {
$(this).addClass('error');
valid = 0;
} else {
$(this).removeClass('error');
}
});
if (valid === 1) {
// submit form
} else {
console.log('error');
return false;
}
});
您可能需要更改選擇器和條件,以檢查除空輸入之外的其他內容,但這些輸入很容易。
我不太確定它們應該是什么,因為您的輸入位於問題的表格中,對於我所知的所有內容可能都包含一個form
標記。
您還可以為輸入錯誤添加一些樣式,以在表單提交失敗時突出顯示它們:
input.input.error {
border: 1px solid red;
}
我使用id作為選擇器來做到這一點,但是如何使用class作為選擇器呢?
$('.conf_prodnum')
點代替哈希將對類而不是id起作用。
使用循環訪問包含類輸入的每個元素,並像這樣檢查您的輸入:
var inputs= $('.input ')
for(x in inputs){
x = inputs[x];
//do whatever you want
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.