Custom jQuery not working on Wordpress Ninja Forms plugin

ぐ巨炮叔叔 提交于 2021-01-20 20:00:27

问题


I am having some problems when I want to add custom jQuery code that affects the form.

For example when someone clicks an input or radio button another input or element to be hidden or shown.I tried to get a result like console.log('trigger'); when clicked or something else but nothing in dev. console appeared.Also, I tried the following methods:

To call the click event with .on('click', function()... or to call the event with .trigger('click');, or to change the event to change

To embed the script within a file from ninja forms or to put it inside the page at the ending of body tag in footer.php

To change the opening declaration of jQuery to work inside a function like this : (function($) {$(document).ready(function(){.....

I know that I could try another plugin, I tried one and the custom jQuery works but I really like this one and don't know why this is happening ...

Thanks


回答1:


Not sure if you need help with this any more as it's been some time since you posted your question, but this may help others in the future. I had the same/similar issue with not being able to run JS/jQuery on the Ninja Forms and found that it's because Ninja Forms load their forms asynchronously. So, when your document.ready function runs, the form doesn't yet exist and it's not able to bind.

Ninja Forms have their own event ready state that can be used as follows:

jQuery(document).on( 'nfFormReady', function( e, layoutView ) {
    // Your code goes here...
});



回答2:


The event isn't registered simply because the elements you're trying to bind the event to do not exist yet at that moment (on document load). Ninja forms loads the form contents asynchronously, so you'll have to wait until the form is fully loaded and then add your event listeners. This works for me:

var formExists = setInterval(function() {
  if ($(".nf-form-cont").length) {
    // Set your event listeners here, example:
    $("#nf-field-1").click(function(e) {
      console.log("click!");
    }
    clearInterval(formExists);
  }
}, 100); // check every 100ms


来源:https://stackoverflow.com/questions/40875677/custom-jquery-not-working-on-wordpress-ninja-forms-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!