gpt4 book ai didi

javascript - 系统验证无法使用 jQuery 隐藏表单进行工作

转载 作者:行者123 更新时间:2023-12-02 21:23:02 36 4
gpt4 key购买 nike

我在index.php页面中有两个表单,form1包含必需的输入和一个允许隐藏form1并显示form2的验证按钮,form2包含<h1> i am in form2 </h1> ,我已经应用了 jQuery 的验证系统,但它不起作用。

index.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" always required.</title>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">

</head>
<body>
<div id="form1">
<form id="myform">
<label for="field">Required: </label>
<input type="text" class="left" id="field" name="field">
<br/>
<input type="submit" class="add-all" value="Validate!">
</form>
</div>
<div id="form2">
<h1>form2</h1>
</div>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

jQuery 代码

<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({

debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true
}
}
});
$(document).ready(function() {
$("#form2").hide();

$('.add-all').on('click', function(e) {
$("#form1").hide();
$("#form2").show();
})
})
</script>

最佳答案

检查这个工作片段。

// just for the demos, avoids form submit
jQuery.validator.setDefaults({

debug: true,
success: "valid"
});
$("#myform").validate({
rules: {
field: {
required: true
}
}
});
$(document).ready(function () {
$("#form2").hide();
$("#myform").submit(function () {
if ($(this).valid()) {
// Hide form1 and show form 2 when form1 is valid
$(this).hide();
$("#form2").show();
}
})
})
<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>Makes "field" always required.</title>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">

</head>

<body>
<div id="form1">
<form id="myform">
<label for="field">Required: </label>
<input type="text" class="left" id="field" name="field">
<br />
<input type="submit" class="add-all" value="Validate!">
</form>
</div>
<div id="form2">
<h1>form2</h1>
</div>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

</body>

</html>

我删除了您的 click 事件,代之以 submit 事件,因为您需要通过 valid() 函数隐藏/显示表单,而不仅仅是通过click事件。

希望这有帮助!

关于javascript - 系统验证无法使用 jQuery 隐藏表单进行工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60801127/

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