santa
santa

Reputation: 12512

on Click with button in jQuery

I have a function that is being called when a particular element is clicked

$(".clickThis").click(function() {

}

I would like to add an HTML button and when it is clicked also call this function

<input type="button" value="Cancel">

Do I need to add a class name to it or is there a way to target it but element?

Can I add second trigger to call my function like this:

$(".clickThis, button").click(function() {

Upvotes: 0

Views: 467

Answers (5)

Stuart
Stuart

Reputation: 66882

You can do a union of jquery selectors using "," as you've shown.

However, as pointed out in comments (and other answers), button itself is not a selector.

For maintainability of code it might be better to give your button an id and to use that - or to assign the clickThis class to the button.

Upvotes: 1

Andbdrew
Andbdrew

Reputation: 11895

you can also make a button element, give it a class like:

<button class="clicksy">Click Me!</button>

and then write a function to grab clicks and do stuff like:

$("button.clicksy").click(function(){
      /* do stuff */
});

Upvotes: 1

Chandu
Chandu

Reputation: 82903

Adding an ID would be better and fastest. Something like:

<input id="cancelButton" type="button" value="Cancel"> 

and then

$(".clickThis, #cancelButton").click(function(){ 
  //Your Code here..
});

If you want to call it with out changing the HTML, try this:

$(".clickThis, :button[value='Cancel']").click(function(){ 
  //Your Code here..
});

Upvotes: 3

Dr.Molle
Dr.Molle

Reputation: 117324

Use

$(".clickThis, input[type='button']")

The way you have it now it will match the <button>-element, not a input with type "button"

Upvotes: 1

Naftali
Naftali

Reputation: 146302

yes you can do that :-)

look here for info abt jQuery mult selectors

so you can do:

$(".clickThis, input:button").click(function() {

Upvotes: 2

Related Questions