Search code examples
jqueryjquery-callback

Attaching custom jQuery function on document ready and on element change


I have a function which hides or shows elements with a given class name:

$.fn.questionDetails = function(base_element, details_yes_no) {
  var details_element = '.' + base_element + '_details';
  var radio_element = '#' + base_element + '_' + details_yes_no;

  if ($(radio_element).attr('checked')) {
    $(details_element).show();
  } else {
    $(details_element).hide();
  }
}

I want to attach/bind this function so that it is called with the two parameters when the page is loaded and when a given radio button group is changed. At the moment I'm using the following code to accomplish this:

$(function() {
  // $.fn.questionDetails defined here, in same scope

  $.fn.questionDetails('question1', 'yes');
  $('input:radio[name=question1]').change().questionDetails('question1', 'yes');
}

The first function call works fine - when the page is loaded the question1_details panel will either be shown or hidden. However, the function does not seem to be called correctly when I change which radio button is selected, nor does it work when I modify the change() line to be this:

$('input:radio[name=question1]').change($.fn.questionDetails('question1', 'yes'));

I want to be able to say "call this function, with these parameters, when the page loads and when a given radio button group is changed", with the least amount of repetition. What is the best way to go about this? I'm relatively new to jQuery, so it's possible I'm doing things the 'wrong' way from the start.

Edit: Should have mentioned this originally - I'm using jQuery 1.7.1.


Solution

  • If you want to assign a call to a function that takes parameters (other than the event) to an event handler, you'll need to wrap that call in an anonymous function, like so:

    $('input:radio[name=question1]').change(function() {
        $.fn.questionDetails('question1', 'yes')
    });
    

    Why? Because the change() function expects a function reference to be passed to it. When you do change($.fn.questionDetails('question1', 'yes')) you're passing the result of calling $.fn.questionDetails('question1', 'yes') to the function, rather than a function reference.