Sunday, September 25, 2011

JQuery Click Event

In this article we will learn how JQuery click events work

Example 1: Show Alert on html button click using JQuery Event (Live Demo)
I have a simple html button control, whose id is "btnClickMe" on click of this button we will display alert.
<button id="btnClickMe">Click Me to Display Alert</button>

JQuery script for showing alert on button click
<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $("#btnClickMe").click(
            function () {
                ShowAlert();
            }            
        );


    });


    function ShowAlert() {
        alert("Alert message on click");        
    }
</script>

Explanation of how things are working here

Step 1: Defining document.ready function.
    $(document).ready(function () {

    });
Whenever we are putting our JQuery code inside this code block means, we are instruction browser to execute JQuery code only when page is loaded and it is ready to execute JQuery code.

Question: Can i put JQuery code directly without even putting it in document.ready function.
Answer: Yes you can do, but in that case you need to be sure that your control is loaded before your JQuery code tries to access it, otherwise you may receive error.

Step 2: Create a Alert function which can be called on button click event.
Note: This is a simple alert function, which is a common javascript alert function.

    function ShowAlert() {
        alert("Alert message on click");      
    }

Step 3: Write button click event to call alert
        $("#btnClickMe").click(
            function () {
                ShowAlert();
            }            
        );
Please note here #btnClickMe is button id on whose click event we are going to show alert.
Watch Live Demo



Example 2: Show Alert on asp.net button click using JQuery Event
I have a asp.net button control, whose id is "btnClickMe" on click of this button we will display alert.

<asp:Button ID="btnClickMe" runat="server" Text="Click Me" />


JQuery script for showing alert on asp.net button click<script language="javascript" type="text/javascript">
    $(document).ready(function () {

        $("#<%=btnClickMe.ClientID%>").click(
            function () {
                ShowAlert();
            }            
        );

    });

    function ShowAlert() {
        alert("Alert message on click");      
    }
</script>



I will be discussing more JQuery examples in JQuery example series.

No comments:

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape