same function for two buttons in jQuery

ANP picture ANP · Sep 28, 2010 · Viewed 19.3k times · Source

I have two buttons: btnAdd and btnUpdate. I have written a jquery function for button btnUpdate to validate some fields in the web page like:

$(function() {

  $('#<%=btnUpdate.ClientID %>').click(function() {
    code here
    });
});

I want to do the same thing when btnAdd is clicked. So I have to write the same function again for btnAdd. Is there other way to avoid this?

(If I write one javascript function and call the same function in the button click event of both buttons, it's fine. But is there any way using jQuery?)

Answer

naivists picture naivists · Sep 28, 2010

Just make a selection of two buttons, separated by a comma: ("#add, #update").click... Looks like this in your code:

$(function() { 

  $('#<%=btnUpdate.ClientID %>, #<%=btnAdd.ClientID %>').click(function() { 
    code here 
    }); 
});