0

In a plugin I use there is the code below:

;(function ( $, window, document, undefined ) {
    $.fn.wc_variation_form = function() {
    var $form = this;
    $form.on( 'change', '.variations input:radio', function() { 
        //code which I want to trigger from elsewhere
    });
});

From my own code, I need to trigger the code located where //code which I want to trigger from elsewhere is. I can run change() for that, but I don't understand what exactly is $form in the code above. Is it a function? If so how can I run change() on these radio buttons from my own code?

1 Answer 1

3

$.fn is actually a reference to jQuery.prototype. So what you are doing is adding a wc_variation_form method to all jQuery objects.

Inside this function, this is the jQuery object the method was called on. So, for example:

$('#myForm').wc_variation_form();

In the function, this will be $('#myForm') and therefore the event will be bound to that function. Since this is a delegated event, it will only trigger if you change a radio button inside the form.

To trigger the event, you can use .trigger('change') (or just .change()) on the radio button you want.

$('#yourRadioButton').change();
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks @Rocket Hazmat that's what I tried earlier but it doesn't work and that's where I started questioning whether I should run change() on my form instead of my radio button. I tried both, first I tried on the radio button $( 'input[value="Every 1 month"]' ).change(); then I tried on the form $( '.variations_form' ).change(); , none of them works :(
@drake035: You need to trigger the event on the radio button. That's what jQuery is looking for before running the callback. Can you show an example with some HTML to show how it doesn't work? As long as your radio button is located in your form (and as a child of .variations), it should work.
I tested on a fresh install and it works indeed, something is messing around in my actual project so I need to find what it is. Thanks!
@drake035: Are there any other event handlers? Maybe one is conflicting.
Actually jQuery was included twice and for some reason it messed at least with this particular uh.. event handler :D Guess I need to take some structured lessons in jQuery, thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.