【问题标题】:How to clear a textbox based on a checkbox using Javascript如何使用Javascript清除基于复选框的文本框
【发布时间】:2013-11-25 11:56:38
【问题描述】:

如果与之关联的复选框未选中,我正在尝试用 javascript 编写代码(以避免在服务器上触发验证)以清除文本框。

我有这个代码...

    <input type="checkbox" id="chkOTHER" onclick="document.getElementById('txtOtherFlag').value='';" />
    <asp:TextBox ID="txtOtherFlag" runat="server" AutoPostBack="True" CausesValidation="True" ValidationGroup="ValidationGroup1"></asp:TextBox>

问题是复选框内的 Javascript 没有触发删除文本框中的值。即使这样有效,它也是不正确的,因为无论是否选中复选框,每次触发复选框时它都会将文本框空白。

我只需要在客户端解决这个问题。

谢谢

[更新]

根据要求,这是我的整个 ASPX 页面减去与问题无关的部分...

    <%@ Page Language="C#" MasterPageFile="~/Attendance/Attendance.master" AutoEventWireup="true" CodeFile="ClassAttendance.aspx.cs" Inherits="Attendance_ClassAttendance" 
        Title="Class Attendance" Culture="en-AU" %>
    <%@Register TagPrefix="tecnq" TagName="ResetPassword" Src="~/Controls/ResetPassword.ascx" %>
    <%@Register TagPrefix="tecnq" TagName="ContactLog" Src="~/Controls/ContactLogKPI.ascx" %>

    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

...
we go now to my panel and table ...
...

    <asp:panel ID="PanelPreStart" runat="server" Visible="false" Enabled="false" >
    <table runat="server" id="tblPreStart" style="width: 649px; height: 543px; border-right: activecaption thin solid; border-top: activecaption thin solid; border-left: activecaption thin solid; border-bottom: activecaption thin solid; background-color: white; background-image: none;">

...
we now go to the checkbox and textbox controls within a customvalidator ...
...

        <tr>
            <td id="tdDocs" runat="server" style="table-layout: fixed; visibility: visible; overflow: auto; border-collapse: separate; font-size: 12pt; vertical-align: top; text-align: left; font-weight: bold; font-family: Arial; background-color: transparent; width: 799px; background-image: none;" colspan="2">
                <strong>What documents will be required for today's tasks?<br /></strong>
                    <span style="font-size: 9pt">(Please ensure supporting documentation is attached)</span>
                <asp:CustomValidator ID="CustomValidator12" runat="server"
                        ErrorMessage='Tick one of the "Documents required today" section tick boxes.' OnServerValidate="CustomValidator12_ServerValidate" ValidationGroup="ValidationGroup1" Font-Names="Arial" Font-Size="9pt">*</asp:CustomValidator><br />
                    <table style="width: 651px; font-weight: bold; font-size: 10pt; font-family: Arial;">
                        <tr>
                            <td style="font-size: 10pt; font-family: Arial; height: 22px; font-weight: bold; width: 247px;">
                                <strong>
                                    <asp:CheckBox ID="chkJSEA" runat="server" Text="JSEA" Width="200px" Font-Names="Arial" Font-Size="10pt" ValidationGroup="ValidationGroup1" /></strong></td>
                            <td style="height: 22px; font-weight: bold; font-size: 10pt; width: 278px; font-family: Arial;"><asp:CheckBox ID="chkRISKA" runat="server" Text="Risk Assessment" Width="200px" Font-Bold="True" Font-Names="Arial" Font-Size="10pt" ValidationGroup="ValidationGroup1" /></td>
                            <td style="height: 22px; font-weight: bold; font-size: 10pt; width: 121px; font-family: Arial;"><asp:CheckBox ID="chkWMS" runat="server" Text="Work Method Statement" Width="200px" Font-Bold="True" Font-Names="Arial" Font-Size="10pt" ValidationGroup="ValidationGroup1" /></td>
                        </tr>
                        <tr>
                            <td style="font-size: 12pt; width: 247px; font-family: Arial; height: 22px;">
                                <strong>
                                    <asp:CheckBox ID="chkSOP" runat="server" Text="Safe Operating Procedures" Width="200px" Font-Names="Arial" Font-Size="10pt" ValidationGroup="ValidationGroup1" /></strong></td>
                            <td style="height: 22px" colspan="2">
                                <label><input type="checkbox" id="chkOTHER" runat="server" />Other </label>
                                <asp:TextBox ID="txtOtherFlag" ClientIDMode="Static" runat="server" AutoPostBack="True" CausesValidation="True" ValidationGroup="ValidationGroup1"></asp:TextBox>
                            </td>
                        </tr>
                    </table>
            </td>
        </tr>

...
and much further down is the javascript/jquery stuff, after the end of the Panel above and after the content placeholder
...

    </table>
    </asp:panel>

    <script src="https://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(function(){
            $("#chkOTHER").change(function(){
                if(!$(this).prop("checked")){
                    $("#txtOtherFlag").val('');        
                }
            });
        });

...
some other javascript functions here which work
...

//        $(document).ready(function() {
//            $("#chkOTHER").change(function() {
//                if ($(this).not(":checked")) {
//                    $('.TheTextBox').val("");
//                } 
//            });
//        });
    </script>
</asp:Content>

上面我有 Karl 和 Juan 的变体 jquery 函数。

对此的任何帮助都非常感谢并被采纳。到目前为止,我已经尝试了所有这些方法,但当我取消选中该复选框时,我仍然无法清除该文本框。

提前谢谢你

【问题讨论】:

  • 可能是onclick="if(!this.checked) this.form['txtOtherFlag'].value='';"
  • 根据我在下面评论的错误,这不起作用。同样的错误,不同的方法,即:form[]。我的控件不在表单中。它们位于面板内的表格中。也许“runat”在这里造成了问题?但我需要在 c# 中进行智能感知
  • 讨厌,表单控件应该在表单中,因为如果您的代码失败,它会提供一些非常好的后备选项。无论如何,如果您不使用表单,那么 onclick="if(!this.checked) document.getElementById('txtOtherFlag').value='';" 或在 jQuery 中:onclick="if(!this.checked) $('txtOtherFlag').val('');"
  • @RobG 我尝试了您在上面解释的两种变体,但仍然没有任何乐趣。 ID 没有呈现为默认值,如 CheckBox1、TextBox1 等。它们仍然与上面提到的名称相同。我将在 Karl 评论的下方发布我的最新尝试。

标签: javascript jquery asp.net checkbox webforms


【解决方案1】:

首先像这样将 ClientIDMode ="Static" 添加到您的文本框中

<asp:TextBox ID="txtOtherFlag" ClientIDMode="Static" runat="server" AutoPostBack="True" CausesValidation="True" ValidationGroup="ValidationGroup1"></asp:TextBox>

这是为了避免在您的文本框中使用一个类,并且能够使用您的文本框,其 id 为“txtOtherFlag”

然后,从您的复选框中删除 onclick 事件

<input type="checkbox" id="chkOTHER"/>

现在在

<script type="text/javascript">
$(function(){
    $("#chkOTHER").change(function(){
        if(!$(this).prop("checked")){
            $("#txtOtherFlag").val('');        
        }
    });
});
</script>

【讨论】:

  • 正如我上面所说的......警告25验证(ASP.Net):属性'ClientIDMode'不是元素'TextBox'的有效属性。
  • 是的,我用过几次:msdn.microsoft.com/en-us/library/…
  • 你是什么意思“添加到你的标签”?
  • 对不起,我没有注意到脚本标签显示不正确
  • 对不起,伙计,它仍然不起作用。这是我所做的... 并在我的
【解决方案2】:

通过使用 jQuery 选择器来响应复选框的检查更改事件,考虑不显眼的 JavaScript,如下所示:

<asp:TextBox ID="txtOtherFlag" runat="server" AutoPostBack="True" 
         CausesValidation="True" ValidationGroup="ValidationGroup1" 
         CssClass="TheTextBox" />

$(document).ready(function() {
    $("#chkOTHER").change(function() {
        if ($(this).not(":checked")) {
            $('.TheTextBox').val("");
        } 
    });
});

注意:我添加了一个CssClass 属性以允许 jQuery 更轻松地选择正确的TextBox,以防表单上存在或将会更多。类选择器允许您避免在使用母版页和丑陋的嵌入式代码块语法 (&lt;%= ... %&gt;) 时发生的潜在服务器控件名称错误。

【讨论】:

  • 谢谢Karl,但你能详细说明一下我应该把那个jquery放在哪里吗?什么叫它?我注意到文本框控件上没有触发它的事件,那么它是如何工作的?对不起,这一切都是新手。
  • @LoftyWofty - $(document).ready(function() 在页面的 DOM 完成加载时触发,它立即将点击​​事件连接到 chkOTHER 复选框。当复选框选中值更改时,$("#chkOTHER").change(function() { 行内的代码将触发并运行if ($(this).not(":checked") 逻辑,确定复选框是否未选中;如果是这样,那么最后$('.TheTextBox').val(""); 清除文本框中的文本。
  • 所以现在有$(this).not(":checked") vs !this.checked。 ;-)
  • @RobG - 明白了,想在整个示例中使用 jQuery 来保留它,以免混淆 OP,但我感谢您的输入。 :-)
  • @LoftyWofty - 在你的页面中试试这个:&lt;script type="text/javascript"&gt; $(document).ready(function() { $("#chkOTHER").change(function() { if ($(this).not(":checked")) { $('.TheTextBox').val(""); } }); }); &lt;/script&gt; &lt;input type="checkbox" id="chkOTHER" checked="checked" value="Other" /&gt; &lt;asp:TextBox ID="txtOtherFlag" runat="server" AutoPostBack="True" CausesValidation="True" ValidationGroup="ValidationGroup1" CssClass="TheTextBox" Text="Blah blah blah" /&gt;
【解决方案3】:

您可以在清除文本之前查看复选框是否被选中:

onclick="if(this.checked===true){document.getElementById('txtOtherFlag').value=''};" />

【讨论】:

  • 嗯,不应该是 '==' 而不是 '===' 吗?无论如何它也没有用.. 消息:'document.getElementById(...)' is null or not an object
  • 你需要检查你的TextBox的ID。我敢打赌,它在实际网页上已更改,这就是您收到该错误的原因。
  • @LoftyWofty - 三等号是有效的 JavaScript,因为 JavaScript 会尝试将类型转换为其他类型以“帮助”你。例如,在 JavaScript 中 2 == "2" 将返回 true,因为 JavaScript 将数字 2 转换为字符串,然后进行比较导致 "2" 等于 "2"。而对于三等号 (===) 运算符,2 === "2" 将返回 false,因为不会将数字 2 转换为字符串。希望这会有所帮助。
  • @LoftyWofty 要能够使用它,请记住在您的文本框中设置 ClientIDMode="Static" 以便 ID 在呈现时不会更改
  • @JuanC。该控件是 ,它没有那个 ClientIDMode 属性。对不起
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 2014-01-10
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多