admin管理员组

文章数量:1422077

I am trying to code in javascript (to avoid validation triggers at the server) to clear a text box if the checkbox associated with it is unchecked.

I have this code ...

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

The problem is the Javascript inside the checkbox is not triggering to remove the value in the text box. Even if this worked, it's incorrect as it would blank out the text box every time the checkbox is triggered whether it is checked or not.

I need to resolve this in the client side only.

Thank you

[UPDATE]

As requested, here is my entire ASPX page minus sections not relevant to the problem ...

    <%@ 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=".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>

I have both Karl's and Juan's variant jquery functions above.

Any help with this has been greatly appreciated and taken on board. I've tried them all so far and I still cannot get that textbox from clearing when I un-tick the checkbox.

Thank you in advance

I am trying to code in javascript (to avoid validation triggers at the server) to clear a text box if the checkbox associated with it is unchecked.

I have this code ...

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

The problem is the Javascript inside the checkbox is not triggering to remove the value in the text box. Even if this worked, it's incorrect as it would blank out the text box every time the checkbox is triggered whether it is checked or not.

I need to resolve this in the client side only.

Thank you

[UPDATE]

As requested, here is my entire ASPX page minus sections not relevant to the problem ...

    <%@ 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./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>

I have both Karl's and Juan's variant jquery functions above.

Any help with this has been greatly appreciated and taken on board. I've tried them all so far and I still cannot get that textbox from clearing when I un-tick the checkbox.

Thank you in advance

Share Improve this question edited Nov 13, 2013 at 4:36 LoftyWofty asked Nov 13, 2013 at 2:54 LoftyWoftyLoftyWofty 871 silver badge8 bronze badges 4
  • Maybe onclick="if(!this.checked) this.form['txtOtherFlag'].value='';". – RobG Commented Nov 13, 2013 at 3:04
  • That didn't work as per the error I mented below. Same error, different method ie: form[]. My controls are not in a form. They are in a table within a panel. Maybe the "runat" is causing problems here? But I need that for intellisense in c# – LoftyWofty Commented Nov 13, 2013 at 3:15
  • Nasty, form controls should be in a form as it provides some really good fallback options if your code fails. Anyhow, if you aren't using a form then onclick="if(!this.checked) document.getElementById('txtOtherFlag').value='';" or in jQuery: onclick="if(!this.checked) $('txtOtherFlag').val('');" – RobG Commented Nov 13, 2013 at 3:20
  • @RobG I tried both variants you've explained above and again no joy. The IDs have not rendered to defaults like CheckBox1, TextBox1, etc. They are still the same names as mentioned above. I'll post my latest attempts below where Karl is menting. – LoftyWofty Commented Nov 13, 2013 at 3:41
Add a ment  | 

3 Answers 3

Reset to default 3

Consider unobtrusive JavaScript by using a jQuery selector in reaction to the checkbox's check changed event, like this:

<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("");
        } 
    });
});

Note: I added a CssClass attribute to allow for jQuery to more easily select the correct TextBox, in case there are or will be more on the form. Class selectors allow you to avoid the potential server control name mangling that happens when using master pages and the ugly embedded code block syntax (<%= ... %>).

you can see if the checkbox is checked before clearing your text:

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

First add ClientIDMode ="Static" to your textbox like this

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

this is to avoid using a class in your textbox and to be able to use your textbox with the id "txtOtherFlag"

then, remove the onclick event from your checkbox

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

now add the following inside your < script > tag

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

本文标签: jqueryHow to clear a textbox based on a checkbox using JavascriptStack Overflow