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:
Post a Comment