tags:

views:

83

answers:

3

Is there any method to have the same coding for the click function of two different id elements in one click function?

For example,I have two link elements with ids, myFormsTabSubmitted and formStatusSubmitted. Both the link is of same functionality. When I click both these links, the same div element("submitted") is showed,and other divs are hidden.

So instead of writing two click functions, one for myFormsTabSubmitted and another for formStatusSubmitted, can I have one click function for both? Like

$('#myFormsTabSubmitted #formStatusSubmitted').click(function(){
   $('#allMyForms').hide();
   $('#draftedMyForms').hide();
   $('#submittedMyForms').show();
   $('#myFormsTab').find(".selected").removeClass();
   $('#myFormsTabSubmitted').addClass("selected");
  });
+4  A: 

Just use the comma separator in the selector:

$("#myFormsTabSubmitted, #formStatusSubmitted").click(function() {
  // do stuff
});
cletus
+4  A: 

Certainly! The simplest change to your code would be to add a comma:

$('#myFormsTabSubmitted, #formStatusSubmitted').click(...);

You can also store a reference to your click handler and add it to multiple selections:

var myHandler = function () { ... };
$('#myFormsTabSubmitted').click(myHandler);
$('#formStatusSubmitted').click(myHandler);
Blixt
+1  A: 

Obviously the comma is the way to go, but I'd like to point out that functions in any language are designed for what you are asking, which is to write the code once for multiple items. I think jquery's documentation gives the impression that functions must follow events, which they don't. You could go with:

function formSubmit() {
                        $('#allMyForms').hide();
                        $('#draftedMyForms').hide();
                        $('#submittedMyForms').show();
                        $('#myFormsTab').find(".selected").removeClass();
                        $('#myFormsTabSubmitted').addClass("selected");
}

$('#myFormsTabSubmitted, #formStatusSubmitted').click(formSubmit);

or

$('#myFormsTabSubmitted').click(formSubmit);
$('#formStatusSubmitted').click(formSubmit);

This way, if you wanted to use that function for yet another event, you won't have to squeeze it in, especially if it's not an onClick.

Anthony
Your syntax is wrong. It should instead be: $("#myFormsTabSubmitted, #formStatusSubtmitted").click(formSubmit);
Joe Chung
Updated to `.click(formSubmit);` instead of `.click(formSubmit(););`
gnarf
Thanks gnarf. I was having trouble finding the right way to do that, further proving my point.
Anthony