簡體   English   中英

無法使用Java語言添加類

[英]Unable to addClass using Javascript

我想通過在驗證時(即在Submit上)添加一個類來為所有空文本框設置樣式,但我的代碼無法正常工作。 不知道它是腳本還是customvalidator。 我只想使用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(sender, args) {
        var target = document.getElementById(sender.controltovalidate.ClientID);
        if (target.value != "") {
            target.removeClass("validate");
        }
        else {
            target.addClass("validate");
        }
        args.IsValid = "";
    }  

嘗試這個。 簡單的方法。

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM