Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

same function for two buttons in jQuery

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?)

like image 263
ANP Avatar asked Sep 28 '10 07:09

ANP


3 Answers

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 
    }); 
}); 
like image 60
naivists Avatar answered Oct 20 '22 11:10

naivists


We call this Refactoring and it's something that will help you all the way, read more about, invest in yourself and buy the fantastic one and only Refactoring book

in your case, you should do this:

$(function() {

  $('#<%=btnUpdate.ClientID %>').click(function() {
        validate($this);
    });
  $('#<%=btnAdd.ClientID %>').click(function() {
        validate($this);
    });    

});

function validate(myButton)
{
    // code here
}

As you should always do.

but as jQuery you can have selectors with multiple inputs, so all you need to do is:

$('#<%=btnUpdate.ClientID %>, #<%=btnAdd.ClientID %>').click(function() { 
    validate($this);
}
like image 31
balexandre Avatar answered Oct 20 '22 10:10

balexandre


There are two ways.

(1) Select both elements at once and apply the event handler to them:

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

(2) Give the function a name, rather than leaving anonymous:

function clickHandler() {
  // code here
}

$('#<%=btnUpdate.ClientID %>, #<%=btnAdd.ClientID %>').click(clickHandler);
like image 8
mpen Avatar answered Oct 20 '22 10:10

mpen