Tuesday 20 December 2011

Show/Hide div using jQuery

Jquery is very useful plugin while developing websites. Its well known now. I know , you all are thinking that why
I am posting such simple solution again? this is so simple. Right na,
I am thinking same as you before doing this and checking it on all browsers.
Lets do this,

I have a div by name 'divTest' with some controls which I want to be access in my code page .cs/.vb
for that I need to apply attribute as 'runat=server' , like this


<div id="divTest" runat="server">
-
-
</div>

now jQuery code to hide/ show this div
lets add some more stuff. I want to display div on checkbox checked event

then the jQuery function will be -




 function HideDiv() {
            var ckh = $('#chkTest').attr('checked');
            var row = $('#divTest');     

            if (ckh == true) {
                row.hide();
         
            }
            if (ckh == false) {
                row.show();
            }
            return true;
        }

and finally the checkbox to hide/show div


<asp:CheckBox ID="chkTest" runat="server" onclick="HideDiv();"/>


This is fine.but now the problem comes when we hide this div from my code (.cs/.vb)

I will put simple code


divTest.visible=false

but this is wrong. If you click on checkbox then this will not display your div.
so the solution is

I have to set style of this div like


to hide -  divTest.Style.Add("display", "none") or
to show -  divTest.Style.Add("display", "block")

thats it!!

Happy Programming!!

2 comments:

  1. Hay Rohi can u start from beginning. I am completely new to jquery. i.e. From where i download jquery, n how to install. First tell me why it is used?

    ReplyDelete
  2. Hey Hi RahuDe, Thanks for posting. If you are beginer then you should read tutorials, books and do some practice of jQuery.

    JQuery is simple plugin. you can download it from Google once you add this js file on your project then you can execute jQuery code.
    JQuery is used to do client side coding on your web page. This is very useful language.

    ReplyDelete