Chudz
Chudz

Reputation: 160

function is not defined WordPress jQuery

I have a js file with a function inside called showProduct.

In my HTML document I have a submit button which has this javascript:

onclick="showProduct(document.getElementById('suggest1').value);"

This gets the value of an input field with the id of suggest1 and is then passed to the function showProduct. This works fine! But as soon as I add this before & after my jquery:

(function($) { .... })(window.jQuery);

I get: Uncaught ReferenceError: showProduct is not defined at HTMLButtonElement.onclick

Any ideas on how I can get this to work? I need to put all the jQuery in this function to get it work with WordPress.

Thanks

Upvotes: 1

Views: 1075

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

When you use an on* event attribute the function you're calling has to be in scope of the window. When you place your code in that IIFE that is no longer the case.

<button class="foo">Foo</button>
(function($) {
  $('.foo').click(function() {
    var value = $('#suggest1').val();
    // do something with the value here...
  });
})(window.jQuery);

One thing to note here is that the button click will submit any parent <form> elements, so you may need to instead hook to the submit event of that form if you do not want to submit it immediately.

Upvotes: 1

Related Questions