a blog for those who code

Tuesday, 16 December 2014

Check which button is clicked in Asp Net Web Application using jQuery

In this post we will show you how to check which button is clicked in Asp Net web application using jQuery. On every web page you might have number of buttons and each button is dedicated for some jobs. In order to take the correct action, you need to know which button has been clicked.

In this post we will assume we have two buttons (Button 1 and Button 2).

<asp:Button Class="Class1" runat="server" Text="Button 1"/>
<asp:Button Class="Class2" runat="server" Text="Button 2"/>

Now we will add a jQuery API or else we can also download jQuery file and add in our application.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

Now after adding the jQuery API we will write a jQuery code to attach the click events on the buttons inside a script tag.

<script type="text/javascript">
   $(document).ready(function () {
        $('.class1').bind('click', function () {
             alert('You have clicked Button 1');
        });
        $('.class2').bind('click', function () {
             alert('You have clicked Button 2');
        });
   });
</script>

According to the jQuery API Documentation

.bind() - Attach a handler to an event for the elements.

PC : http://api.jquery.com/bind/

$('.class1').bind('click', function () line attaches the click event to all the elements which has a class named class1.

If you don't want to have different classes for different buttons but want a single action for everything you might have to change your button like

<asp:Button Class="button" runat="server" Text="Button 1"/>
<asp:Button Class="button" runat="server" Text="Button 2"/>

and your jQuery as

<script type="text/javascript">
     $(document).ready(function () {
        $('.button').bind('click', function () {
             alert('You have clicked ' + $(this).val() + ' button');
        });
     });
</script>

$('.button').bind('click', function () line attaches the click event to all the elements which has a class named button.


You can even attach a double click event to the button element like the below code

<script type="text/javascript">
  $(document).ready(function () {
    $('.button').dblclick('click', function () {
      alert('You have double clicked ' + $(this).val() + ' button');
    });
  });
</script>

.dblclick() method attaches the double-click event to the specified element. Double-click is the event that occurs when the mouse is over the element and is double-clicked.


Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License