我是初学者,在动态添加输入字段Reference From: Validate Dynamically Added Input fields时,通过验证并提交时不能转到其他页面
关注脚本示例。
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
通过验证时点击提交按钮不能动作=“/ action_page_post.php”
和HTML代码
<form class="commentForm" method="get" action="/action_page_post.ph">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
答案 0 :(得分:0)
我所做的更改
on('submit')
更改为submitbutton.onclick
$('.commentForm').submit();
,如果验证为真,则执行原因:由于您使用的是event.preventDefault()
,因此会阻止表单的默认行为,因此不会转到下一页。因此,您必须使用$(form).submit();
手动提交表单
以下代码适用于普通页面,但不适用于 SO Snippet
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('input.submit').click(function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
});
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
$('.commentForm').submit();
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form class="commentForm" method="get" action="action_page_post.php">
<div>
<p id="inputs">
<input type="text" class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
&#13;