Subhamoy
Subhamoy

Reputation: 116

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.

Upvotes: 1

Views: 2224

Answers (4)

Murali Murugesan
Murali Murugesan

Reputation: 22619

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>

Upvotes: 2

patel.milanb
patel.milanb

Reputation: 5992

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

Upvotes: 2

Govinda Rajbhar
Govinda Rajbhar

Reputation: 3034

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.

Upvotes: 1

Linga
Linga

Reputation: 10555

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

Upvotes: 1

Related Questions