【发布时间】:2019-05-17 19:20:30
【问题描述】:
我在一个 div 上有 3 个输入(重复多次),我想验证如果用户在 coreid 上输入一个值,则有必要插入金额,并在全名上有一个值(它是用 id 给出的自动从 sql 中获取,如果它没有值.. id 不正确)这在同一行,因为它们具有所有相同的类和名称,它会进行验证,但它们是否在同一行与否.. 即使我在第一行插入 coreid,在第三行插入全名,在第二行插入金额,它也会提交。 请帮忙?
$("#myform").submit(function() {
var currentForm = this;
var allinputs = 0;
var coreid = 0;
var fullname = 0;
var amount = 0;
//if all inputs are empty
$(this).find('input.cardField').each(function() {
if ($(this).val() != "") allinputs += 1;
});
if (allinputs) {
//checks if coreid has a value
$(this).find('input.cardField.id').each(function() {
if ($(this).val() != "") coreid += 1;
});
//checks if fullname has a value
$(this).find('input.cardField.name').each(function() {
if ($(this).val() != "") fullname += 1;
});
//checks if amount has a value
$(this).find('input.cardField.cardAmount').each(function() {
if ($(this).val() != "") amount += 1;
});
//if user inserts an id it must have a value on name
if (coreid) {
var empty = $(this).parent().find("input.cardField.name").filter(function() {
if ($(this).val() != "") fullname += 1;
});
if (fullname) {
//the name is given when the user inserts the id
alert("it has a name, the id is correct");
} else {
bootbox.alert('Please insert a valid id');
return false;
}
//the user inserts an amount but not an id
} else {
bootbox.alert('Please insert an employee id');
return false;
}
} else {
//the user can continue if he confirms
bootbox.confirm("Empty fields, Do you want to continue?",
function(result) {
if (result) {
currentForm.submit();
}
});
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="number" name="coreid[]" class="form-control cardField id">
<input type="text" name="fullName[]" class="form-control cardField name">
<input type="number" name="amount[]" class="form-control cardField amount">
</div>
<div>
<input type="number" name="coreid[]" class="form-control cardField id">
<input type="text" name="fullName[]" class="form-control cardField name">
<input type="number" name="amount[]" class="form-control cardField amount">
</div>
<div>
<input type="number" name="coreid[]" class="form-control cardField id">
<input type="text" name="fullName[]" class="form-control cardField name">
<input type="number" name="amount[]" class="form-control cardField amount">
</div>
如果用户插入三个输入之一,则他必须插入三个值... 不管其他行(其他 div)是否为空。
【问题讨论】:
标签: javascript jquery html validation