【发布时间】:2018-11-08 03:42:54
【问题描述】:
我有两个 Jquery 函数,其中一个将在单击按钮时向表单插入一个新的动态行,另一个函数将验证该行中的单元格。
var currentItem = 11;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td><select class="form-control select2 productSelect" name="product'+currentItem+'" id="product'+currentItem+'" style="width: 100%"> <option disabled selected value> -- select a Product -- </option>'+ <?php foreach ($productData as $product) { echo "'<option value=" . $product->product_id . ">" . $product->product_name . "</option>'+";}?> '</select> </td><td><input class="form-control quantitySelect" name="quantity'+currentItem+'" id ="quantity'+currentItem+'"type="text" /></td><td><input class="form-control" name="freeIssue'+currentItem+'" id="freeIssue'+currentItem+'" type="text" /></td> <td align="center"><button class="btn btn-danger" name="close" id="close" onclick="SomeDeleteRowFunction(this)"><i class="fa fa-close"></i></button></td></tr>';
$('#data').append(strToAdd);
});
这里我将类名productSelect作为第二个函数的标识符进行验证。但它无法识别该类,并且验证不适用于我通过上述函数添加到表单的行。
$('.productSelect').change(function () {
var elementID = $(this).attr("id");
var numberPart = elementID.split("t", 2);
if ($(this).val() != null ) {
$('#quantity'+ numberPart[1]).prop('required',true);
}
});
这就是整个代码的样子
<script type='text/javascript'>
$(document).ready(function() {
$('.productSelect').change(function () {
var elementID = $(this).attr("id");
var numberPart = elementID.split("t", 2);
if ($(this).val() != null ) {
$('#quantity'+ numberPart[1]).prop('required',true);
}
});
var currentItem = 11;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td><select class="form-control select2 productSelect" name="product'+currentItem+'" id="product'+currentItem+'" style="width: 100%"> <option disabled selected value> -- select a Product -- </option>'+ <?php foreach ($productData as $product) { echo "'<option value=" . $product->product_id . ">" . $product->product_name . "</option>'+";}?> '</select> </td><td><input class="form-control quantitySelect" name="quantity'+currentItem+'" id ="quantity'+currentItem+'"type="text" /></td><td><input class="form-control" name="freeIssue'+currentItem+'" id="freeIssue'+currentItem+'" type="text" /></td> <td align="center"><button class="btn btn-danger" name="close" id="close" onclick="SomeDeleteRowFunction(this)"><i class="fa fa-close"></i></button></td></tr>';
$('#data').append(strToAdd);
});
});
</script>
【问题讨论】:
-
你能分享你的完整代码吗?
-
@rv7 是的,现在我已经编辑了我的帖子并插入了我的完整代码
标签: javascript jquery forms validation