I am running the following code which is:
iframedoc.getElementsByTagName('form')[0].submit();
I need to execute code as soon as the form is done being submitted. Does the submit() block, or do I need some other way to determine when the form has been submitted?
No, triggering a form submit does not block or return anything useful. It merely tells the browser to create a request which will render a new page. However, with an iframe the onload event can be used to handle the response from the form submit after it has loaded.
iframedoc = iframe.contentDocument;
iframe.onload = function(e) {
alert('frame loaded');
// read its url, content, etc...
};
iframedoc.getElementsByTagName('form')[0].submit();
// immediately returns undefined and your code proceeds
Since JavaScript runs in a single thread, you won't see the 'frame loaded' alert until all of your subsequent code has completed, the browser submits the form, and the onload event triggers.
Related
I am placing my HTML form inside of another system and cannot get my own function to run during the submit event.
I cannot use Form onSubmit='foo' as the system has a script that automatically populates the onSubmit of any form placed inside of it (overwriting anything placed beforehand).
Additionally, this system has its own validation that it performs at the submit event.
So I am trying to use the EventListener to run my function as well as the system one at form submission, however it is not working. The console.log doesn't even show up.
I see that the system function has:
document.forms[0].submit();
So it must be firing before my function causing mine to never run as the system function either submits or cancels the submit it appears.
Here is my eventListener code.
var formRef = document.forms.myForm;
myForm.addEventListener('submit', function(evt) {
evt.preventDefault();
console.log('event fired');
//checkBlanks function loops through the form looking for blanks,
//if a field is blank it changes it to red and then fires the system's
//confirmation dialogue. Else it fires the system's confirmation dialogue.
checkBlanks();
});
In the event that it matters, my form is inside of the system's form and the submit button is located in the system's portion of the window. I tried to addEventListener the button but it says it cannot get property of undefined reference.
All you need to do is to call the form tag or you call an #id to it
enter code here
document.querySelector('form').addEventListener('submit',execute);
function execute(e){
console.log('submitting...');
e.preventDefault();
}
I have a JavaScript that generates a form with an onsubmit event handler. The form is defined like this:
document.writeln('<form action="#" id="loginForm" onsubmit="processLoginForm(this);">');
In this processLoginForm() function I am basically printing a form value and returning:
function processLoginForm(form) {
var userName = form.uname.value;
document.writeln("username = "+userName+"<br>");
return false;
};
When this form is loaded, the browser loading is complete and done. Loading the page is done by the browser. But when I click on the button to submit the form, my code is processed but my browser is still trying to load something that it shows this loading icon and never stops. I tried returning true, false, or nothing in processLoginForm() function, but it has no impact.
How can I make my browser to stop loading when my submit handler is done?
I'd recommend not putting your function inline into the HTML. Instead do this:
HTML
<form action="#" id="loginForm">
JavaScript
document.getElementById('loginForm').onsubmit = function(event){
event.preventDefault();
//continue to process the form
}
The event.preventDefault() method which is attached to the event argument that is automatically passed in event listeners will cancel the default action of the handler. In this case, trying to load a page located at /# (according to your form action).
I'm trying to write an unobtrusive function on a submit button without the use of jQuery and the like. I have the following bit of code in my HTML form:
document.getElementById('help_submit').onclick = function (){
window.alert("You clicked on the Submit Button on the Help Request form.");
};
And I'm trying to use on the following HTML button:
<input type="submit" id="help_submit" value="Submit Help Request" />
However when I try to fire the event, the form doesn't pop up with the Message Box and submits anyway.
I check the developer tools in Chrome and I see the following error:
Uncaught TypeError: Cannot set property 'onclick' of null
Where did I go wrong with the coding?
It seems likely that you are running your Javascript too early before the DOM has loaded and thus document.getElementById('help_submit') does not find the DOM element because it is not yet in the page. You can fix this by moving the script that contains this code to right before the </body> tag so all DOM elements will be present when the script runs. For more details on this issue, consult this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it.
In addition, your submit handling code needs to prevent the default action of the submit button or the form will submit anyway. Though, if you don't want the form to submit, then you should just stop using a submit button and use a regular button.
In addition to moving the script to the end of the DOM, I'd suggest you change your event handling code to this:
document.getElementById('help_submit').addEventListener('click', function (e) {
e.preventDefault();
window.alert("You clicked on the Submit Button on the Help Request form.");
});
Working demo: http://jsfiddle.net/jfriend00/vcjtv0kz/
I'm not experienced in JavaScript, but, following on the comment and the answer already given, try changing your code the following way:
Remove the given code (it will be used differently at the next steps).
Inside the script tag inside the head element, try creating two functions called, say, initialization and message:
function initialization()
{
element = document.getElementById('help_submit');
element.addEventListener( 'click', message, false );
}
function message()
{
window.alert("You clicked on the Submit Button on the Help Request form.");
}
At the end of this script tag, write the following:
window.addEventListener( "load", initialization, false );
I have an aspx page (the JQuery.js is called in the masterpage for this). Now this is linked to the http://code.jquery.com/jquery.js
In this page I have an updatepanel which is dynamically loading different usercontrols which in turn have their own JS files loads (using scriptmanager). Now on a partial postback I am losing JQuery functions (for instance .val returns undefined).
[code]
function pageLoad(){
//whatever you want to do on partial postback
//alert('partial handler');
$(jutb).watermark('Username or Email address');
$(jptb).watermark('Password');
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
// Called when async postback begins
function InitializeRequest(sender, args) {
// alert("You are in the InitializeRequestHandler function."); // breakpoint here
}
// Called when async postback ends
function EndRequestHandler(sender, args) {
// this function is run after an Ajax partial postback occurs
loadUsername();
loadPassword();
if (args.get_error() != undefined)
alert("There was an error" + args.get_error().message);
return;
}
[/code]
my page load is being called in the partial postback. (i.e. I can alert to it.)
I have a linkbutton which triggers some JS code. after the partial postback if I try it .val returns undefined.
Any ideas why JQuery is being lost?
When you get the response back from the server into your update panel, all event handler bindings you did the first time the page loaded are broken, because those are new elements now, even though they satisfy the same selection criteria.
You can try to re-run your event handler binding - you can create some kind of init JS function that you'd call in your EndRequestHandler.
Other way, and probably better, would be to use jQuery's on to bind your elements to event handlers. Take a look here on how to use it:
https://api.jquery.com/on/
I use AJAX to load an external HTML file, containing a form, into another HTML file. The form HTML looks something like this:
<form id="..." name="..." onsubmit="postUsingAJAX(x,y,x); return false;">
Loading works fine. However, the onSubmit code is not executed when the form is submitted, same thing with onClick handlers on the submit button; no event listeners seems to be triggered. Is this the way things work when HTML is loaded through AJAX or am I doing something wrong?
A possible work-around would be to do:
theFormObject.addEventListener('submit', function...)
but I can't figure out how to make the form NOT submit after the callback is fired. How can I make it wait for a return value (or rather, feed it "return false" no matter what happens in the callback function)?
Any ideas?
It looks like an error in function postUsingAJAX. Code "return false" will not executes. To continue properly work after error you should use try..catch statement. Example:
function postUsingAJAX() {
try {
// dangerous code
} catch (e) {
// report about error
}
}
<form onsubmit="postUsingAJAX(); return false;">
If you're using AJAX, my guess is that you don't want the form to take the user to a new page - you want it to call the processing page and update the current page accordingly. What you should do instead is create the entire form without any <form> tags. Then, using the <button> tag (example: <button id="whatever">Whatever</button>) attach a click event listener to that button to do the AJAX stuff. That's the way that I always do AJAX calls with a form that the user is filling in.