jQuery perform a single action (method) for multiple elements

Asked

Viewed 304 times

3

I have a form where an action can be executed several times by different elements, I wonder if you have how to put everything in a single call. For example:

$("#campo_01").change(function(){
    $("#frmForm").submit();
});

$("#campo_02").change(function(){
    $("#frmForm").submit();
});

$("#campo_03").change(function(){
    $("#frmForm").submit();
});

Of course, it’s not that simple, because the functions are more complex, with a few more lines. The above example is only to understand what I am wanting.

Is it possible to put everything together, for example:

$("#campo_01 #campo_02 #campo_03").change(function(){
    $("#frmForm").submit();
});
  • Use the multi-element selector, ,, comma.

1 answer

3


You can separate by commas inside the selector string like this:

$("#campo_01, #campo_02, #campo_03").change(function(){
    $("#frmForm").submit();
})

or still with the selector ^=, which means id "starting with":

$('[id^="campo_"]').change(function(){
    $("#frmForm").submit();
})
  • 1

    Interesting that, regex-like selectors.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.