0

I have the following code:

$('#form_field, #button').bind('change click', function() {
// take action
});

It works fine. However, I want to trigger the same action when 'change' is used for '#form_field' and 'click' for '#button' (not when 'click' is used for '#form_field').

I know that can be done using the following code:

$('#form_field').bind('change', function() {
// take action
});

$('#button').bind('click', function() {
// take action
});

However, I do not want to repeat all the code that is inside the function (// take action). It would look ineffective and I will need to edit it twice every time I make changes to it.

Any ideas?

Thanks in advance

3 Answers 3

12

How about:

var myCoolFunction = function() {
  // take action
};
$('#form_field').bind('change', myCoolFunction);
$('#button').bind('click', myCoolFunction);

??

Sign up to request clarification or add additional context in comments.

2 Comments

Why don't u (and Nick Spiers in his answer) don't use $('#button').click(myCoolFunction) instead of $('#button').bind('click',myCoolFunction)? Same with $('#button').bind('change',myCoolFunction) and $('#button').change(myCoolFunction). As I'm new to JQuery: Is there a specific reason? ~Chris
Not really, it saves a whopping 1 function call.. inside of jQuery $.fn.click = function(fn) { return fn ? this.bind('click', fn) : this.trigger('click'); }; ( although it isn't set directly that way, look @ line 3098 in jQuery-1.3.2.js )
3

This should do the trick:

$('#form_field').bind('change', takeAction);

$('#button').bind('click', takeAction);

function takeAction () {
    //take action
};

Comments

0

I'm not too sure it's that great an idea to find a way around this. If they both do the same thing, just make a function for them to call on the required events.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.