Two jquery functions at the same time

I have two jquery that I am running and I want to combine them in one line. Here is an example of what I am trying to do.

    ​$(function(){
    $('input').each(function(){
        if ($(this).is(':checked')) {
           $(this).after('this is checked');
        }
    });
    $('input').click(function(){
        if ($(this).is(':checked')) {
           $(this).after('this is checked');
        }
    });
});​

      

Now both functions do the same thing, one is done to check for any inputs checked against the backend, and the other for user clicks.

I thought if I could combine them in a statement like this,

$('input').bind('each click');

      

but I noticed that even this won't work with everyone. Any ideas?

Thank!

+3


source to share


2 answers


Just name the function.

function handler() {
    if ($(this).is(':checked')) {
       $(this).after('this is checked');
    }
}

      



then use it in both situations:

$(function(){
    $('input').each(handler);
    $('input').click(handler);
});​

      

+1


source


You cannot bind a method each

because it is not an event.

Assign the function to a variable so that it can be reused:

​$(function(){

  var markChecked = function() {
    if ($(this).is(':checked')) {
       $(this).after('this is checked');
    }
  };

  $('input').each(markChecked).click(markChecked);
});​

      



Another approach, which is sometimes used, is to fire a click event on each element to force an initial check:

​$(function(){
  $('input').click(function() {
    if ($(this).is(':checked')) {
       $(this).after('this is checked');
    }
  }).click();
});​

      

This, of course, assumes that firing the click event has no side effects. If you have already bound another click event handler to any of the elements, this will trigger that event handler to be called.

+1


source







All Articles