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?)
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
});
});
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);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With