请有人帮助我,我真的坚持了一整天。 我有一个 php 表单(多页),具有不同类型的输入(单选、复选框等)。我需要的是:
如果用户没有填写必填字段并按下继续按钮,他应该在该字段的旁边或上方收到一条错误消息。
如果他忘记填写某些字段,则不应清除其他输入字段(因为我不想让他/她厌倦再次回答所有这些问题)
这是我迄今为止使用 JQuery 插件尝试过的:(抱歉,我无法粘贴所有代码,因为它太长了)
<form name="MovieSurvey" id="formId" action="page2.php" method="post" />
<fieldset id = "q1"> <legend class="Q1"></legend>
<label> What is your gender?<span>*</span></label>
<div class="fieldset content">
<div class="error_message_holder"></div>
<Input type = 'radio' Name ='q1' value = 'male'>Male
<Input type = 'radio' Name ='q1' value = 'female'>Female
</div>
</fieldset>
....
....
<input type="submit" name= "continue1" value="Continue" />
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$('#formId').validate({ // initialize the plugin
rules: {
q1: {
required: true,
},
q2: {
required: true,
},
q5: {
required: true,
},
q6: {
required: true,
}
},
errorPlacement: function(error, element) {
error.html('Please fill this field');
if(element.closest('.fieldset content').find('label.error').length==0){
error.insertBefore(element.closest('.fieldset content').find('.error_message_holder'));
}
}
});
});
</script>
</div>
</fieldset>
</body>
</html>
它工作得很好,唯一的问题是错误消息显示在单选按钮和标签之间! (这是当我不写 errorPlacement: 函数部分时),为了修复它,我添加了放置部分,但现在它什么也不显示!
有人可以帮我解决这个问题吗?
谢谢
最佳答案
引用OP:
"If user didn't fill required fields and pressed the continue button, he should receive an error message BESIDE or ABOVE that field."
你让这种方式变得比需要的更加复杂。
只需使用
insertBefore
,而不是默认的insertAfter
,在errorPlacement
回调。errorPlacement: function (error, element) { // error.insertAfter(element); // default function error.insertBefore(element); },
然后使用
errorElement
选项更改label
进入div
,这将消息强制放在自己的行上。这会按照您的请求在您的单选按钮组上方显示一条消息。errorElement: 'div' // default is 'label'
引用OP:
"If he forgot to fill some fields, other input fields should not be cleared (since I don't want him/her to get bored of re-answering all those questions again)"
这已经是默认行为。该插件不会也不能更改输入到字段中的任何值。它仅阻止提交并显示/隐藏错误消息。
演示:http://jsfiddle.net/9bkjsg8o/
文档(所有选项):http://jqueryvalidation.org/validate
<小时/>注释:
您的form
元素过早关闭,并显示 />
在开始标签中...
<form name="MovieSurvey" id="formId" action="page2.php" method="post" />
form
是一个容器元素,因此已经有一个名为 </form>
的结束标记.
您的开始标签应如下所示...
<form name="MovieSurvey" id="formId" action="page2.php" method="post">
关于单选按钮的 jQuery 验证插件错误消息位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26023470/