0

Trying to set up an on click event listener for a submit button. Here is my jQuery code -

(function($) {
  console.log('working');

  $("#submit").on('click', function(event) {
    event.preventDefault();
    console.log('test');
  });
})(jQuery);

Here is the HTML -

<input type="submit" id="submit" value="Submit Result" />

I'm doing this on a Word Press site. I know the .js file is linked correctly because I see the 'working' console log.

What is wrong with the code?

Edit -

Just tried this -


  $(window).on('click', function() {
    console.log('test');});

And that works. Is there an issue with how I have my ID set up in the HTML?

jfc
  • 361
  • 3
  • 15

3 Answers3

0

Use 'jQuery' instead of '$' in WordPress to avoid conflict

(function(jQuery) {
  console.log('working');

  jQuery("#submit").on('click', function(event) {
    event.preventDefault();
    console.log('test');
  });
})(jQuery);
Bilal Naseer
  • 156
  • 1
  • 2
  • 16
0

The code you wrote is fine. I assume you linked the Javascript file on the top of the page - which doesn't work out.

You have to add the <script> tag on the bottom of your html for it to work.

    <input type="submit" id="submit" value="Submit Result" />

    // Rest of HTML

    <script src="link/to/script.js"></script>
  </body>
</html>
maersux
  • 151
  • 6
0

The submit button will still run the forms POST action. You can hide the real submit button, and create a button to trigger the submit (usually after validation).

As for comments about $ and jQuery conflicts etc... Using the encapsulation code below you should be fine to use either one.

<button id="preSubmit">Submit</button>
<input style="display:none;" type="submit" id="serverSubmit">

(function ($) {
    $(function () {  //document.ready

        $("#preSubmit").on('click', function(e) {
            e.preventDefault();
            $("#serverSubmit").trigger("click");
        });     

    });
})(jQuery);
Brian Patterson
  • 1,615
  • 2
  • 15
  • 31