I'm using jQuery's load() function to change content on a page dynamically. It's a application with different 'levels' but the URL never changes.
It's working fine except for the final screen I'm using. I've got a form with text inputs etc that I need to create some form validations for but I can't get on('submit') to work after the page load. I am using a callback function on the load function and I do run some simple jQuery CSS, etc. to content that is on the final_page.php so I know that it's successfully running the function AFTER the content is loaded.
I'm trying to simply just apply a preventDefault() to the form for now to confirm that it's working correctly but the form submits every time I get to that final page so it looks like the on() function doesn't get bound to the form selector.
Is there some sort of conflicting with submit and load?
$('#main_content').load('final_page.php', function(){
$('#main_content').css({'height':'auto','padding-bottom':'25px','background':'#086c8c'});
$('#hidden_input').attr('value', 'complete');
//GOOD UP TO THIS POINT
$('#final_form').on('submit',function(e){
e.preventDefault();
});
});
Related
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
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
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().
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
I have the following:
$(document).ready(function(){
// bind 'myForm' and provide a simple callback function
$('#form').ajaxForm(function() {
alert("Works!!!");
});
});
The problem is that when I dynamically add the form to the HTML the script is not working. If the form is there from the beginning the form is submitted with Ajax and works as expected.
What is the problem here?
the problem is that $(document).ready() only gets fired when the page is initially loaded. If you add the form dynamically to the page, you'll need to make the call to setup the form again.
Alternatively, you can use the livequery plugin to 'listen' on the page for when a new form element is added to the page and to automatically setup the form for you.