views:

60

answers:

4

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  A: 

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);
Mark
+1  A: 

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 
    }); 
}); 
naivists
you should mention that Refactoring is a huge step in developing.
balexandre
A: 

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);
});
Paul D. Waite
+1  A: 

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