我创建了一个注册表单,现在我正在尝试在字段上放置null验证。 所有字段都位于一个表中,如:
<table border="0" cellspacing="5" width="100%">
<tr>
<td width="50%" valign="top">
<span id="ctl00_PageBody_lblFname">Prénom</span>
<strong><font color="#FF0000">*</font></strong><br />
<input name="ctl00$PageBody$txtFname" type="text" id="ctl00_PageBody_txtFname" rel="First Name" />
<br />
<span id="ctl00_PageBody_lblLname">Nom</span>
<strong><font color="#FF0000">*</font></strong><br />
<input name="ctl00$PageBody$txtLname" type="text" id="ctl00_PageBody_txtLname" rel="Last Name" />
</td>
</tr>
</table>
现在使用jquery我正在尝试创建一个遍历所有文本框的泛型函数,如果它们是空的,它会显示一条提到字段名称的消息:
var Msg = "Please provide values for :";
var nullFieldTracked = 'false';
$('input[type="text"], select').each(function () {
if (this.value == '' && this.hasAttribute("rel")) {
nullFieldTracked = 'true';
Msg += '\n - ' + $(this).attr('rel');
}
});
if (nullFieldTracked == 'true') {
alert(Msg);
return false;
}
代码就像魅力一样,我在文本框中添加了'rel'属性以便读取字段名称,但是
现在需求发生了变化,我需要用多种语言启动这个网站,因此它将从资源文件中读取属性,而asp.net不会为'rel'标签创建元资源,所以我正在考虑从最近的Span读取Field Name,但不能跟踪。
请帮助Jquery。
提前多多感谢。
答案 0 :(得分:1)
从最近的范围中检索值
$(this).prevAll("span").first().text()
答案 1 :(得分:0)
不确定您是否可以在.net
的文本字段中添加数据属性如果是,
你可以将span的id存储在输入的data
属性中,每个文本字段应该在其数据属性中保存span id,如
<input name="ctl00$PageBody$txtFname" type="text" id="ctl00_PageBody_txtFname" rel="First Name" data-error-span = '#span1'/>
现在在你的JS
中$('input[type="text"], select').each(function () {
if (this.value == '' && this.hasAttribute("rel")) {
nullFieldTracked = 'true';
Msg += '\n - ' + $($(this).data('error-span')).val();
}
});
另一种选择可能是在数据属性中存储错误 然后JS将是
Msg += '\n - ' + $(this).data('error-message');
也看起来很可读
令人敬畏的Rails:)
答案 2 :(得分:0)
使用.closest() 这给出了最近的选择元素。