user3623053
user3623053

Reputation: 218

enable checkbox only when textbox is not empty asp.net

I need to make visible a checkbox and a text near it only when the textbox is filled. Otherwise it should be invisible.

<p>Telefon:<asp:TextBox ID="txtPhone" runat="server"></asp:TextBox></p>  
<asp:CheckBox ID="CheckBox2" runat="server" Visible="False" Text="bla bla"/>  

It will be ok either code behind or javascript.

Upvotes: 1

Views: 657

Answers (2)

Bill Kindig
Bill Kindig

Reputation: 3622

Mason's answer was partially working for me, meaning the ID's were static and it could hit both conditions within the jQuery. However, my HTML was being rendered with CheckBox2 with a <span></span> element. So I had to do this to make it work.

<p>Telefon:<asp:TextBox ID="txtPhone" ClientIdMode="static" runat="server"></asp:TextBox>  
<asp:CheckBox ID="CheckBox2" ClientIdMode="static" runat="server" Text="blabla" style="display: none;" />

$(function () {
    $('#txtPhone').on('input propertychange paste', function () {
         if ($('#txtPhone').val()) {
                $("#CheckBox2").parent().show();
                }
                else {
                    $("#CheckBox2").parent().hide();
                }
            });
        });

Upvotes: 2

mason
mason

Reputation: 32694

You should do this with JavaScript. This question shows us how to detect when the textbox value changes. This question tells us how to tell if the textbox is empty or not. This demo shows us how to hide and show things with jQuery.

Notice that I made the ClientIdMode="static" for the controls, to avoid having different ID's on the client side than on the server. And instead of using the Visible property on the checkbox, I use the display: none CSS. Visible="false" would not even send the markup for the checkbox to the client, and we need that markup so we can show it without a postback.

<p>Telefon:<asp:TextBox ID="txtPhone" ClientIdMode="static" runat="server"></asp:TextBox></p>  
<asp:CheckBox ID="CheckBox2" ClientIdMode="static" runat="server" Text="bla bla" style="display: none" /> 

$(function() {    
    $('#txtPhone').on('input propertychange paste', function() {
        if($('#txtPhone').val()){
            $("#CheckBox2").show();
        }
        else{
             $("#CheckBox2").hide();
        }
    });
});

Upvotes: 1

Related Questions