gpt4 book ai didi

javascript - Jquery 验证插件(.validate)在动态表单(循环表单)中不起作用

转载 作者:行者123 更新时间:2023-12-03 06:45:45 24 4
gpt4 key购买 nike

我正在使用 Jquery 验证插件来验证动态表单。我收到了所需的错误消息,但主要问题是所需字段是否为空,无论条件提交按钮仍然有效。如果必填字段为空,我无法停止提交。这是我的一小段代码。

HTML:

<form class="pa-form" action="confirmed" method="post" id="my-form">
<fieldset>
<?php for($i=1;$i<=3;$i++){ ?>
<div class="flabel-control">
<input data-toggle="floatLabel" data-value="" name="myForm[first_name][]" class="firstname form-control" type="text" id="first-name<?=$i?>" required placeholder="First name" spellcheck="false">
</div>
<div class="flabel-control">
<input data-toggle="floatLabel" data-value="" name="myForm[last_name][]" class="firstname form-control" type="text" id="last-name<?=$i?>" required placeholder="Last name" spellcheck="false">
</div>
<br>
<?php };?>
<div class="btn-holder">
<input type="submit" id="submitBtn" class="btn btn-default text-uppercase" value="Confirm">
</div>
</fieldset>
</form>

JS:

$("#my-form").validate({
validClass: "valid",
errorClass: "error",
rules: {
'myForm[first_name][]': "required",
'myForm[last_name][]': "required",
},
messages: {
'myForm[first_name][]': "First name is required",
'myForm[last_name][]': "Last name is required",
}
}
});

最佳答案

jquery-validate 要求每个元素都有唯一的名称。因此,请将 for 循环索引放入名称中。

    <?php for($i=1;$i<=3;$i++){ ?>
<div class="flabel-control">
<input data-toggle="floatLabel" data-value="" name="myForm[first_name][<?=$i?>]" class="firstname form-control" type="text" id="first-name<?=$i?>" required placeholder="First name" spellcheck="false">
</div>
<div class="flabel-control">
<input data-toggle="floatLabel" data-value="" name="myForm[last_name][<?=$i?>]" class="firstname form-control" type="text" id="last-name<?=$i?>" required placeholder="Last name" spellcheck="false">
</div>
<br>
<?php };?>

您不需要在rules中专门列出元素,因为插件会自动处理元素中的required属性。但如果你愿意,你可以这样做:

var rules = {}, messages = {};
for (var i = 1; i <= 3; i++) {
rules['myForm[firstname][' + i + ']'] = 'required';
messages['myForm[firstname][' + i + ']'] = 'First name is required';
rules['myForm[lastname][' + i + ']'] = 'required';
messages['myForm[lastname][' + i + ']'] = 'Last name is required';
}
$("#my-form").validate({
validClass: "valid",
errorClass: "error",
rules: rules,
messages: messages
}
});

关于javascript - Jquery 验证插件(.validate)在动态表单(循环表单)中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37740724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com