Add Add Add

How to use click event for anchor tag and button tag simultaneoulsy in jQuery?

4.2k Views Asked by At

I'm using jQuery 1.9.1 in my project. I've following HTML :

<button type="button" id="btn_add" class="btn btn-primary">Add</button>
<a class="btn_delete" href="#"><i class="icon-trash"></i></a>

I want to display the same alert message if user clicks on a icon enclosed in anchor tag with class "btn_delete" or click on a button having id "btn_add".

For this I tried following code but it didn't work out for me.

$(document).ready(function() {
  $("button#btn_add.btn_delete").on("click", function(event) { 
    event.preventDefault();
    alert("This action has been temporarily disabled!")
  });
});

Can someone please help me in this regard please?

If you want any more information regarding the issue I'm facing please let me know.

Thanks in advance.

7

There are 7 best solutions below

1
mahip_j On BEST ANSWER
   **Approach #1**
   function doSomething(){
    //your code
   }

   $('#btn_add').click(doSomething);
   $('.btn_delete').click(doSomething);

   **Approach #2**
   $("#btn_add,a.btn_delete").on("click", function(event) { 
      event.preventDefault();
      alert("This action has been temporarily disabled!")
   });
0
PeterKA On

Your code is quite close to what it should be. Change:

$("button#btn_add.btn_delete")

To:

$("#btn_add,a.btn_delete")
0
Anoop Joshi P On

You can use , to have multiple selectors.

$(".btn_delete i,#btn_add").on("click", function(event) {
    event.preventDefault();
    alert("This action has been temporarily disabled!")
});
0
Ashish Panchal On

You can have both the HTML Tag in the jQuery selector as below:

$(document).ready(function() {
  $("button#btn_add, a.btn_delete").on("click", function(event) { 
    event.preventDefault();
    alert("This action has been temporarily disabled!")
  });
});

Hope this helps!

0
Lawrance On
$(document).ready(function() {
    $("#btn_add,.btn_delete").on("click", function(event) { 
        event.preventDefault();
        alert("This action has been temporarily disabled!")
   });
});
0
Tim Wißmann On

Additionally to the other answers:

Your current selector will find elements like this:

<button id="btn_add" class="btn_delete">Foo</button>
0
Ankit Gupta On
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

 $(document).ready(function() {
 $("button#btn_add, a.btn_delete").on("click", function(event) { 
 event.preventDefault();
  alert("This action has been temporarily disabled!")
});
});

</script>