简体   繁体   中英

Hide a TextBox on checking a checkbox server control in ASP.NET/C# - using Jquery or Javascript

I have been trying to hide a Textbox if a Checkbox is checked again display it if the checkbox is unchecked Source Code goes like below.

   <asp:CheckBox ID="ShortStoryCheckBox" runat="server" />
<asp:TextBox ID="LeadTextBox" runat="server" Height="77px" TextMode="MultiLine" 
        Width="370px"></asp:TextBox>

So my aim is to hide LeadTextBox if ShortStoryCheckBox is checked. If it is unchecked again I have to display it. To accomplish that I tried below piece of JQuery. Below the Id's I have used are HTML id that I got from source view of browser.

<script type="text/javascript">
    $("#ctl00_PlaceHolderMain_Home_ShortStoryCheckBox").change(function () {
        if (this.checked) {
            $("#ctl00_PlaceHolderMain_Home_LeadTextBox").hide();
        }
        else {
            $("#ctl00_PlaceHolderMain_Home_LeadTextBox").show();
        }
    });
</script>

But it is not working, can anybody please help me how could I do it? or where I am going wrong? Any alternate suggestion to achieve it would also be very helpful.

try with click and prop & some code refactoring

<script type="text/javascript">

$(document).ready(function(){

    $("#<%= ShortStoryCheckBox.ClientID %>").click(function () {
        if ($(this).prop("checked")===true) {
            $("#<%= LeadTextBox.ClientID %>").hide();
        }
        else {
             $("#<%= LeadTextBox.ClientID %>").show();
        }
    });
 });
</script>

working jsfiddle: http://jsfiddle.net/patelmilanb1/AJvJD/

$(document).on("change", "#ShortStoryCheckBox", function () {
    if ($(this).is(":checked")) {
        $("#LeadTextBox").hide();
    } else {
        $("#LeadTextBox").show();
    }
});

Second approach:

$(document).on("change", "#ShortStoryCheckBox", function () {
    $("#LeadTextBox").toggle();
});

Note: you can assign class names to textbox and checkbox for simpler use

You have to use the ClientID of ShortStoryCheckBox and LeadTextBox which gets the control ID for HTML markup that is generated by ASP.NET

$("#<%=ShortStoryCheckBox.ClientID%>").change(function(){
 if($(this).is(":checked"))
 {
    $('#<%= LeadTextBox.ClientID %>').hide();
 }
 else
 {
    $('#<%= LeadTextBox.ClientID %>').show();
 }
});

You can do with this way.

$(document).ready(function() { 
  $('#<%=ShortStoryCheckBox.ClientID%>').bind('click', function() {
    if($(this).is(":checked")) {
      $("#<%=LeadTextBox.ClientID%>").show();
    } else {
      $("#<%=LeadTextBox.ClientID%>").hide();
    }
  });
}); 

i hope this code will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM