12

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

4 Answers 4

23

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 
    }); 
}); 
1
  • you should mention that Refactoring is a huge step in developing.
    – balexandre
    Sep 28, 2010 at 8:03
8

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

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);
}
0

jQuery is a JavaScript framework, not another language, so you can write one JavaScript function here too.

function validateFields(e) {
    code here;
}

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.