Custom jQuery not working on Wordpress Ninja Forms plugin - javascript

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

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...
});

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

Related

JavaScript code not waiting til page loads after button click

I am trying to fill out a form and click submit and then I need to wait until the next page loads and continue working with elements. It seems like the code after the button click happens before the next page appears and the DOM has loaded. I've tried to use a while loop to check the readyState but that doesn't seem to work either. Any suggestions? Here is an example of what I'm trying to do assuming I have the submit button element in variable submitButton.
I've tried to use a while loop to check the readyState but that doesn't seem to work either. Any suggestions? Here is an example of what I'm trying to do assuming I have the submit button element in variable submitButton.
submitButton.click();
var errors = document.getElementsByClassName('error'); // Should be done after new page load
if (errors.length > 0)
{
console.log("There are some errors");
}
Assuming there will be some errors on the next page, there should be a message printed out, but this doesn't happen.
You can use window.onload()
Just pass a function thaz does what your script is currently meant to be doing
The function will be called when the page is loaded so you can use it to implement the functionality you want
encapsulate the whole code inside function i write but for this you would need the jquery
$( document ).ready(function() {
//Your code here
});
For refrence
Document Ready function jquery

How to remove all event listeners made from a specific loaded file?

<div id="loaded-content">
#Scripts.Render("~/someScript.js")
</div>
this appears to be equivalent to
<div id="loaded-content">
<script src="/someScript.js"></script>
</div>
When the above content is loaded with ajax every event listener from someScript.js becomes active and remains, even if the content is later removed via jQuery like so:
$("#loaded-content").remove();
What should be done to prevent the same event listeners from being activated multiple times if the content is constantly loaded and removed? I tried adding a global variable var scriptHasRun = false;, then the following code in someScript.js:
$(document).ready(function(){
if(scriptHasRun){
return;
}
scriptHasRun = true;
<more code>
});
It works for someScript.js, but then came someOtherScript.js that appears to be loaded the same way, so to prevent things in advance I used the same method with another variable var otherScriptHasRun = false; and the second time it gets loaded in the page it no longer works. It started working normally when I removed the check. I'd like to know how to replicate the circumstances of someOtherScript.js, or in case that's normal, what could be causing someScript.js to be loaded multiple times?
I see you are using jQuery. I'm not sure what you have in someScript.js, but you can use
$('#element').off('click', handleClick);
to unbind event from element before attaching it so it does not get attached multiple times.
other option I would try to use is to ad specific event related classes to element to mark them as already having the event attached and use something like the line below to attache the events so you can skip using variable scriptHasRun to check if script has been loaded.
$('#myElemetSelector:not(.boundToEventX)').addClass('boundToEventX').on('click', onElemetClickedFunction);
It's likely because the event listeners in someScript.js are bound to the body and the ones in someOtherScript.js are bound to the elements themselves, so the code that checks if the script has been run before isn't needed on them, but still is for someScript.js.

Jquery Onclick functionality not working for div, as specific loaded after sometime

For <div class="editdiv">Test</div>. Jquery click functionality is added in document.ready function . But editdiv loading in page dynamically with delay.
So when I click on the div. Function is not calling. By using timeout function is working fine.
I need a different approach to solve this functionality.
If your .editdiv is loaded dynamically after your js loading so your click event can't detect it and it will not work, instead you should use event delegation on() to deal with fresh DOM :
$('body').on('click', '.editdiv', function(){
//Your click event code
})
If you want to avoid setTimeout you could use delay with queue callback method :
$('div.scroll-area-blue')
.delay(5000)
.queue(function() {
$(this).enscroll({
showOnHover: false,
verticalScrolling: true,
verticalTrackClass: 'vertical-track-blue',
verticalHandleClass: 'vertical-handle-blue'
});
});
If you will use setTimeout better to use it like :
setTimeout( enscrollDiv, 5000);
function enscrollDiv(){
$('div.scroll-area-blue').enscroll({
showOnHover: false,
verticalScrolling: true,
verticalTrackClass: 'vertical-track-blue',
verticalHandleClass: 'vertical-handle-blue'
});
}
Hope this helps.
It is really difficult to understand whats going wrong from your question. What I guess is you are loading a specific div using Ajax or similar technologies - meaning the div is not available initially.
The way jQuery works is that, it only binds the event to the elements only available at the time the part is executed.
If a <div id='myDiv'></div> is not present when $('#myDiv').click(function(){}) is called, it won't work.
One workaround is to do it like this:
$('body').on('click','#myDiv',function(){});
This registers the click on body and then checks if the clicked element is having a id 'myDiv' or not. We can expect the <body></body> to be present always. So the problem we had with previous code won't happen here.
maybe you're loading the javascript codes before the html elements(tags) are loaded.
try adding the script which includes "document.ready()" before the end tag of the body when all html tags have already finished loading.
I'm hitting targets in the dark. Hope it works for you. It's difficult to generate any solution without analyzing the problematic code......

Is it safe to put all your code inside `$(document).ready`?

I'm using jQuery for a small project I have and it's one of my first times using it. Is it safe to put all my UI code in $(document).ready() ? I'm basically creating a form that pops up when a button is pressed, and the form is processed via AJAX. Basically, when I separate my AJAX function from the functions controlling the UI, the AJAX doesn't work. However, when I put both of them in $(document).ready(), everything works fine. Here's my code. Please ignore my comments, as they were for learning purposes.
$(document).ready(function(){ //ready for DOM manipulation
/*FORM UI*/
var container_form=$('#container_form'); //container form box
var addButton=$('.addButton'); //"+" add button
container_form.hide(); //initially hides form
$(addButton).click(function(){
$(container_form).toggle('fast');
/*SUBMISSION AJAX*/
$('form.ajax').on('submit',function() { //Make form with class "ajax" a JQuery object
var that = $(this), //"that"-current form, "url"-php file, "type"-post, "data"-empty object for now
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){ //search all elements in the form with the attribute "name"
var that=$(this), //legal attribute
name=that.attr('name'); //name of the legal attribute
value=that.val(); //value of text field in legal attribute
data[name]=value; //data object is filled with text inputs
});
$.ajax({
url: url, //url of form
type: type, //type of form
data: data, //data object generated in previous
success: function(response){ //reponse handler for php
if(!response){
console.log("Error");
}
console.log(response);
}
});
return false; //Stops submission from going to external php page.
});
});
});
Generally any selectors such as $('form.ajax')., $('#container_form'), $('.addButton') needs to be in doc.ready to ensure that the DOM is ready before you try to select an element from it, since it may not find the element if the DOM hasn't finished processing. So that pretty much applies to all of your code. If you had a function such as this:
//defines a function
function addThem(first,second)
{
return first + second;
}
You could declare it outside of doc ready, and call it from within doc ready.
$(document).ready(function(){
$('#someInput').val(
addThem( $('#anotherInput').val() , $('#thirdInput').val() )
);
});
The way I think about this, is doc ready is an event, so you should be doing things in response to the "document is now ready for your to query event", not declaring things. Declaring function just says what that function does, but doesn't actually do anything, so it can go outside of the document ready. It'd be pretty silly to declare this function inside of doc.ready since it can be defined at anytime (although it certainly is possible to put it inside doc ready, it just generally clutters things up). Even if it were selecting an element, that code isn't actually running until it is called:
function hideContainer()
{
//this code never runs until the function is called
//we're just defining a function that says what will happen when it is called
return $('#container').hide();
}
$(document).ready(function(){
//here we are calling the function after the doc.ready, so the selector should run fine
hideContainer();
});
Note that the act of wiring up to other events is an action in itself, such as when you subscribed to the click events and form submit events. You are saying, "find the form element with class .ajax, and subscribe to its submit event". You wouldn't want to try and wire up to events of DOM elements until the DOM is done processing. They might not "exist" yet as far as the browser is concerned if it is in the middle of processing the DOM, and thus your attempt to wire up to the click/form submit events may fail. I say may because depending on timing/processing lag it may sometimes work and sometimes not.
There's not only nothing wrong with putting all your code into one $(document).ready(), but there's nothing wrong with putting it into multiple $(document).ready() functions either so that you can separate repeated functionality into individual JS files.
For example, I use $(document).ready() in a script included on all my site's webpages to set up UI elements, prevent clickjacking, etc. At the same time, each page regularly has its own $(document).ready() which sets up page specific user interactions.
It is absolutely OK. If you find yourself needing to abstract your code into multiple function or multiple files, then by all means, but there's nothing wrong with throwing everything in $(document).ready().

How to bind to submit event in jQuery Mobile pages

Tried to bind submit event (or click or whatever) to an element within a jQuery mobile page. What I wanted to do is get the value from an input within an form element within a jQuery page and store it in cookies/localStorage. Every time I come back to this page I want to restore the input field.
Currently I ended up in using this script:
$('.pageClassSelector').live('pageinit', function (e) {
$('.classSelector').submit(function () {
var q = $('.inputClassSelector').val();
// store to localStorage ...
});
// load from localStorage ...
$('.q').val(lastSearchString);
});
This approach is documented there http://jquerymobile.com/test/docs/api/events.html
Since it seems possible that identical pages are hold in the DOM, ID selectors are not quite useful. My problem now is that everytime I navigate to this page the submit event is bound again and thus results in storing DIFFERENT (!) values. The submit event seems to be fired multiple times and much more interesting with the value before last.
Am I doing anything completly wrong? Any hints how to do scripting in jquery mobile properly?
TRY1:
I placed now the submit event binding within the pagebeforeshow event like so:
$('#PageId').on('pagebeforeshow', function (e) {
$('.classSelector').on('submit', function () {
var q = $('.q').val();
alert('stored: ' + q);
}
$('.q').val(lastSearchString);
}
But the value going to be stored is still the value before last, when I was navigating the page before. The first time it works as it should.
TRY2:
This is what I have now and it looks like it does that what I want. I select now the current page and select only the form which is a child of this page.
Is this good practice?
$('div:jqmData(id="PageId")').on('pagebeforeshow', function (e) {
$(this).find('#form').on('submit', function () {
var q = $(this).find('#input').val();
localStorage.setItem("key", q);
return true;
});
lastSearchString = localStorage.getItem("key");
$(this).find('#input').val(lastSearchString);
});
Your requirement to load from local storage and store on the page needs to be done by binding to the pagebeforeshow event (look at the section "Page transition events") and not the pageinit event like you are currently doing.
$('.pageClassSelector').on('pagebeforeshow', function (e) {
// load from localStorage ...
$('.q').val(lastSearchString);
});
Furthermore generally each page element (where you have data-role='page') should have a unique ID so you can use that instead of the CSS selector.
Multiple events firing when navigating pages sounds like multiple bindings to me, which is a known problem with jQuery Mobile. Bindings are not unbound when navigating pages, because everything is loaded through AJAX. See for example this StackOverflow Question: Jquery mobile .click firing multiple times on new page visit or my solution.
$('.classSelector').on('submit', function(){})
Try to use the constraction to bind your event to element.
Look likes some data was loaded through ajax request

Categories