无法使用Javascript添加Class
Unable to addClass using Javascript
我想通过在验证时(即在提交时)添加一个类来对所有空文本框进行样式设置,但我的代码不起作用。不确定是脚本还是自定义验证器。我只想使用JS。如果我说
target.style.border="1px solid red";
不过它起作用了。只是无法添加类。
JS:
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function validateTextBox(sender, args) {
var target = document.getElementById(sender.controltovalidate);
var is_valid = target.value != "";
if (is_valid) {
target.removeClass("validate");
}
else {
target.addClass("validate");
}
args.IsValid = is_valid;
}
</script>
ASPX:
<asp:TextBox ID="txtSurname" runat="server"></asp:TextBox>
<asp:CustomValidator ID = "CustomValidator1" runat="server"
ControlToValidate="txtSurname" ValidateEmptyText="true"
ClientValidationFunction="validateTextBox"
></asp:CustomValidator>
CSS:
.validate
{
border:2px solid red;
}
document.getElementById返回一个DOM元素,该元素没有addClass或removeClass API。
参见:元件
要应用类,请尝试(提出想法,请根据确切的业务逻辑进行调整):
target.className = target.className + " validate"
如果我们使用原始JS,我们必须编写原始代码,并忘记addClass或removeClass:-)要删除类,请参见以下答案:使用javascript 删除类
试试这个。简单的方法。
function validateTextBox() {
var target = document.getElementById("#<%= txtSurname.ClientID %>");
**var is_valid = target.value;**
**if (is_valid!="") {**
target.removeClass("validate");
**return true;**
}
else {
target.addClass("validate");
**return false**
}
}
ASPX:
<asp:TextBox ID="txtSurname" runat="server"></asp:TextBox>
<asp:CustomValidator ID = "CustomValidator1" runat="server"
ControlToValidate="txtSurname" ValidateEmptyText="true"
ClientValidationFunction=**"Javascript:return validateTextBox()"**
></asp:CustomValidator>
也许您想使用jquery验证插件?这是一个广泛使用的插件。
<asp:TextBox ID="txtSurname" runat="server" CssClass="toValidate"></asp:TextBox>
jQuery(function() {
// You can specify some validation options here but not rules and messages
jQuery('form').validate();
// Add a custom class to your name mangled input and add rules like this
jQuery('.toValidate').rules('add', {
required: true
});
});
此代码应在表单提交前检查文本框是否为空。
更改var target = document.getElementById(sender.controltovalidate.ClientID);
至:var target = document.getElementById(sender.ClientID);
试试这个。。。
function validateTextBox(sender, args) {
var target = document.getElementById(sender.controltovalidate.ClientID);
if (target.value != "") {
target.removeClass("validate");
}
else {
target.addClass("validate");
}
args.IsValid = "";
}
相关文章:
- 将鼠标悬停在Angular JS中的一个元素上,并将Class添加到另一个元素中
- 如果X与Y的href=匹配,则添加class'活动'-jQuery
- 元素必须单击两次才能添加Class(自定义指令)
- CoffeeScript:如何添加Class,除非
- 无法使用Javascript添加Class
- 带有“;E”;,无法添加Class
- 如何在ng repeat中添加Class
- 单击按钮运行函数并添加Class
- 查找所有禁用的字段并添加Class jquery
- 如何添加class="active"使用Javascript创建菜单栏
- 按顺序向一系列元素添加class
- jQuery:添加Class Active到<与当前页href
- 为具有特定CSS属性的元素添加Class
- 不能为元素添加class
- 添加Class到body>在用户滚动网页后标记
- 单击HTML元素A并用纯JavaScript在B上添加Class
- 为“某些选择”中具有相同父类的所有选项添加Class使用jquery
- 在AngularJs中向多个元素中添加class
- 如果图像宽度小于X,则添加class
- 视频开始时添加class或id