我决定在HTML 5中创建一个向导表单(实际上在这里使用ASP.NET MVC)。我有以下HTML表单:
@using (Html.BeginForm())
{
<div class="wizard-step">
<input type="text" name="firstname" placeholder="first name" />
</div>
<div class="wizard-step">
<input type="text" name="lastname" placeholder="last name" />
</div>
<div class="wizard-step">
<input type="text" name="suffix" placeholder="suffix" />
</div>
<button class="back-button" type="button">
Back</button>
<button class="next-button" type="button">
Next</button>
}
然后我有这个js脚本:
<script type="text/javascript">
$(document).ready(function () {
var $steps = $(".wizard-step");
var index = 0;
var count = $steps.length;
$steps.each(function () {
$(this).hide();
});
$(".back-button").attr("disabled", "disabled");
var $currentStep = $steps.first();
$currentStep.show();
$currentStep.addClass("current-step");
$(".back-button").click(function () {
$currentStep.hide();
$currentStep.removeClass("current-step");
$currentStep = $currentStep.prev();
$currentStep.addClass("current-step");
$currentStep.show();
index--;
$(".next-button").removeAttr("disabled");
if (index == 0) {
$(this).attr("disabled", "disabled");
}
else {
$(this).removeAttr("disabled");
}
});
$(".next-button").click(function () {
var $inputFields = $(".current-step :input");
var hasError = false;
$inputFields.each(function () {
if (!validator.element(this)) {
hasError = true;
}
});
if (hasError)
return false;
index++;
$(".back-button").removeAttr("disabled");
if (index == count - 1) {
$(this).attr("disabled", "disabled");
}
else {
$(this).removeAttr("disabled");
}
$currentStep.hide();
$currentStep.removeClass("current-step");
$currentStep = $currentStep.next();
$currentStep.addClass("current-step");
$currentStep.show();
});
});
</script>
基本上,我想要的是点击Next按钮,它将验证在当前可见DIV内找到的输入元素,而不是整个FORM。是否可以使用HTML5执行此操作?如果没有,也许是jQuery?
如果您有其他人,请在此处分享。非常感谢!
答案 0 :(得分:1)
旧:
var hasError = false;
$inputFields.each(function () {
if (!validator.element(this)) {
hasError = true;
}
});
if (hasError)
return false;
新:
var isValid = false;
$inputFields.each(function () {
isValid = $(this).valid();
});
if (!isValid)
return false;
======================
我也可以在$(document).ready()行下添加这个来使用/添加jquery验证规则:
$("#myForm").validate({
rules: {
lastname: "required"
}
});