好的,这对我来说很难解释,但我会尽我所能。
我有一个单独的表单,我将其拆分为3个单独的步骤,以便用户更轻松地处理数据。感谢jQuery,我很容易通过在dom中隐藏和显示元素来实现这一点,但由于这一点,jQuery在验证最初隐藏的数据时遇到了问题。
请查看以下表单:http://jsfiddle.net/Egyhc/
<form>
<div id="step1" style="display: block;">
<label for="first_name">First Name</label>
<input type="text" value="" name="first_name" id="FirstName"/>
<label for="last_name">Last Name</label>
<input type="text" value="" name="last_name" id="LastName"/>
</div>
<div id="step2" style="display: none;">
<label for="first_name">Address</label>
<input type="text" value="" name="address" id="Address"/>
</div>
<a href="#" id="step1_btn">Continue to step 2</a>
<input type="submit" id="submit_btn" value="Verstuur" style="display: none;" />
</form>
$(function() {
$('#step1_btn').click(function() {
$('#step1, #step1_btn').hide();
$('#step2, #submit_btn').show();
});
});
正如您所看到的,这是一个相当简单的形式,但是当我添加验证时,只有第一个“步骤”有效。第二步没有得到验证。
您可以在下面找到我添加验证的代码:
$(function() {
$('#step1_btn').click(function() {
$('form').validate({
rules: {
first_name: "required",
last_name: "required"
}
});
if($('form').valid()) {
$('#step1, #step1_btn').hide();
$('#step2, #submit_btn').show();
}
});
$('#submit_btn').click(function() {
$('form').validate({
rules: {
address: "required"
}
});
if($('form').valid()) {
return true
}
});
});
任何人都知道,一旦我进入第二步,我怎样才能使验证工作?
答案 0 :(得分:3)
我已在此处提供表单,因为我已对其进行了修改(添加了反向链接)
<form>
<div id="step1" style="display: block;">
<label for="first_name">First Name</label>
<input type="text" value="" name="first_name" id="FirstName"/>
<label for="last_name">Last Name</label>
<input type="text" value="" name="last_name" id="LastName"/>
</div>
<div id="step2" style="display: none;">
<label for="first_name">Address</label>
<input type="text" value="" name="address" id="Address"/>
</div>
<a href="#" id="step1_btn">Continue to step 2</a>
<a href="#" id="step2_btn" style="display:none;" >Back to step 1</a>
<input type="submit" id="submit_btn" value="Verstuur" style="display: none;" />
</form>
<强> JS 强>
$(function(){
$('form').validate({
rules: {
first_name: "required",
last_name: "required",
address: "required"
}
});
$('#step1_btn').click(function() {
if($('form').valid()) {
$('#step1, #step1_btn').hide();
$('#step2, #submit_btn').show();
$('#step2_btn').show();
}
});
$('#step2_btn').click(function() {
$(this).hide();
$('#step1, #step1_btn').show();
$('#step2, #submit_btn').hide();
});
$('#submit_btn').click(function() {
if($('form').valid()) {
return true
}
});
});