我有一个包含4行输入字段的表单,如下所示:
<tr>
<td><input name="company01" id="company01" /></td>
<td><input name="description01" id="description01" /></td>
<td><input name="costs01" id="costs01" class="sum" /></td>
<td><input name="file01" id="file01" /></td>
</tr>
<tr>
<td><input name="company02" id="company02" /></td>
<td><input name="description02" id="description02" /></td>
<td><input name="costs02" class="sum" id="costs02" /></td>
<td><input name="file02" id="file02" /></td>
</tr>
现在,当用户输入行的其中一个输入(例如成本字段)时,应该强制输入公司和描述符(但不是附件)。
文件上传绝不是强制性的。但是,用户必须至少按行完成公司,说明和费用。
有人可以告诉我如何检查至少有一行是否已完成?我将如何使用jQUery Validation Plugin检查其他2是否已完成?
答案 0 :(得分:3)
可以使用必需的方法和dependency expressions
来完成....
rules : {
company01 : { required : "#company02:blank" },
description01 : { required : "#company01:filled" },
costs01: { required : "#company01:filled" },
// now company 2
company02 : { required : "#company01:blank" },
description02 : { required : "#company02:filled" },
costs02: { required : "#company02:filled" }
}
....
答案 1 :(得分:1)
您可以使用"dependency-expression"使一个字段的规则取决于另一个字段的状态。
这是一个有效的例子......
工作演示:http://jsfiddle.net/GMK5V/
<强>的jQuery 强>:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
// other options,
rules: {
field1: {
required: true
},
field2: {
required: '#field1:filled'
}
}
});
});
HTML (还为每个id
添加了input
):
<form id="myform">
<input type="text" name="field1" id="field1" />
<input type="text" name="field2" id="field2" />
</form>
答案 2 :(得分:0)
默认情况下,jQuery validate不会检查禁用的输入。虽然依赖关系表达式完全符合您在问题中所要求的内容,但我认为值得问问自己,如果您的表单在没有公司名称的情况下进行描述是否合理。根据您想要的用户体验,最好从禁用描述,成本和文件上载开始,清楚地告知用户这些字段不能单独使用。然后根据jQuery验证规则的要求标记它们,当它们启用时,它们是必需的。
然后诀窍是在添加公司名称时启用它们。我会像下面这样做:
<强>标记强>
<!-- add a class to the row for ease of dom traversal -->
<tr class="company-row">
<!-- add a class to the company name for ease of selection -->
<td><input class="company-name" name="company01" id="company01" /></td>
<td><input name="description01" id="description01" /></td>
<td><input name="costs01" id="costs01" class="sum" /></td>
<td><input name="file01" id="file01" /></td>
</tr>
<强>的JavaScript 强>
$(document).ready(function() {
$('.company-name').on('keyup', function() {
var $this = $(this);
if($this.val() != '') {
$this.parents('.company-row').find('input').removeAttr('disabled');
} else {
$this.parents('.company-row').find('input').not('.company-name').attr('disabled', 'disabled');
}
});
)}
这应该可以解决问题,但诚然,我没有测试过我刚写过的任何东西。你也可能遇到这样一种情况,即某人已经停止了公司描述,试图提交,获得了该字段的验证消息,删除了公司名称,验证消息也不会消失(他们可能不会能够提交表格)。我忘记了如何解决这个问题,但最简单的方法是在整个验证器上调用.resetform()
,这将删除任何验证消息。如果您在提交时调用它,那可能会有效。
答案 3 :(得分:0)
没有使用validate方法解决它。我所做的是,检查一行中的所有输入,看看它们是全是空的还是全部填写完毕。如果任何行不匹配,我只需创建一个警告对话框。
不是很好,但至少它完成了验证。