Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change an object visibility with javascript using a checkbox?

i'm really sorry if this question have been asked before but I couldn't find it.

Working on a ASP.NET/C# web application.

i am creating a label in the code behind and adding it to the page (all coded in the code behind and not in design page)

Now I have a check-box I want to change the visibility of the label depending if the checkbox is checked (show) or if not (hide).

I tried to use an update panel. But since the label is generated in code I have to generate it again everytime there is a partial postback. and I don't want that.

Is there a way to do this with javascript to avoid post-backs? other solutions are also appreciated.

Thank you very much for any help

like image 800
Y2theZ Avatar asked Jul 06 '26 04:07

Y2theZ


1 Answers

Put this code in the page Load.

if (!Page.IsPostBack) {
    Label lbl = new Label();
    lbl.ID = "lbl";
    lbl.Text = "Test";
    this.Controls.Add(lbl); 

Add the reference to the jQuery javascript and place it as HTML below.

<asp:CheckBox runat="server" ID="chk" />
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("#chk").change(function () {
            if (this.checked)
                $("#lbl").hide();
            else
                $("#lbl").show();
        });
    });
</script>

Try to use AJAX (jQuery) in case you need to create dynamic controls.

like image 190
Vicente Jr Avatar answered Jul 08 '26 17:07

Vicente Jr