0

I have a single shared jQuery function that checks a RadioButton selection: if 1 is selected, it hides a span, otherwise it shows it.

This shared function is called both on startup and on Change, because on startup, it needs to do the same thing. The startup works, but the onChange reference does NOT work:

JS_OBJ = {

    toggleTier : function() {

        if ($('input[name="tier"]:checked').val() == 'Y_YES')
        {
            $('#tierSpan').hide();
        }
        else
        {
            $('#tierSpan').show();
        }       

    },

    // this is called from document.onReady - it comes here, OK
    onReady : function() {      

        // on startup, toggle Tier - works OK
        this.toggleTier();

        // Also link the radio button Change to this shared function
        $('input[name="tier"]:radio').change(function () {
            alert('About to enter toggle...');
            // NEVER COMES HERE - Object doesn't support this property or method
            this.toggleTier(); 
        });

    }

};
gene b.
  • 6,760
  • 9
  • 49
  • 122

2 Answers2

2

the this is changing value as it is passing thru the different zones. when it is first instantiated, it has a good value, but the radiobutton:change has a different this

I was able to change it get it to work:

    $('input[name="tier"]:radio').change(function () {
        alert('About to enter toggle...');
        self;   //closure
        toggleTier(); 
    });

see this: What underlies this JavaScript idiom: var self = this?

Community
  • 1
  • 1
2174714
  • 288
  • 2
  • 10
1

Inside the change event, this does not refer to the current JS_OBJ, it refers to the current event target in stead. You want to explicitly save your reference to this, so you can use it inside the event.

Example:

onReady : function() {      

    var me = this;
    me.toggleTier();

    // Also link the radio button Change to this shared function
    $('input[name="tier"]:radio').change(function () {
        me.toggleTier(); 
    });

}
Paul-Jan
  • 16,057
  • 58
  • 87