1

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

1
  • 1
    "I need to put all the jQuery in this function to get it work with WordPress" – you don't, really. If you want to keep using $ inside the function, the simplest fix is var $ = jQuery; as the first line inside the function. Commented May 26, 2017 at 13:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.