Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

jQuery – Handling Click Events

4.83/5 (5 votes)
18 Dec 2013CPOL2 min read 54.3K  
jQuery - handling click events

In my previous blog post, we have discussed about interacting with DOM in jQuery. If you didn’t read that, I strongly recommend you to do so before proceeding with this article as this is a continuation of that article. Here is the link jQuery - Interacting with DOM. In this article, we will go over Click Events in jQuery.

Handling Click Events

  • .click(handler(eventObject)) is used to listen for a click event or trigger a click event on an element.
  • Example
    JavaScript
    $(‘#myID’).click(function(){
    alert(‘The element myID is clicked’);
    });

Let’s look at an example. I have a webform where there are 2 TextBoxes, 1 TextArea, 1 Select and 1 Button.

jQuery.1

First, let’s look at how to handle button click event in the traditional way – using JavaScript. First of all, write a function in the script block.

jQuery.3

Then come into HTML and call that function in onclick.

jQuery.2

Run the application and we will get the expected message in the alert box while clicking the button.

jQuery.4

Now let’s examine how to do the same thing using jQuery. We will write a function in the script block and will call that function inside $(document).ready() function. We can use $(‘#SubmitButton’).click() to raise the button click event.

jQuery.5

Run the application and click on the button. We will get the same alert message which we have got previously.

jQuery.6

Now let’s examine how to grab values and display them in click event. For this, we are creating a new div having an id of DivOutput, next to the button.

jQuery.8

Inside the button click event, write the code to grab the FirstName and LastName and show them in the new div. To grab the value in FirstNameTextBox, we can write like $(‘#FirstNameTextBox’).val().

jQuery.9

Go ahead and run the application. Give First Name and Last Name. Click on Submit button. You can see the Full Name next to Submit button as expected.

jQuery.10

Now while understanding Click Events in jQuery, the below question may arise in your mind.

Can we raise a Click Event from another Click Event?

  • Absolutely. We can raise a Click Event from another function.
  • Example
    JavaScript
    $(‘#otherID’).click(function(){
    $(‘#myID’).click();
    });
  • In the above code, Click Event for myID will be fired when the element otherID is clicked.

Reference: Arun Ramachandran (http://BestTEchnologyBlog.Com)


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)