I hesitate to ask this as it is a bit complex, but I will try to make it simple.
I have a page with several form fields.
I submit the page via a submit script (note more is done in this submit script, but I am leaving it out for simplicity
function do_file_form_submit(gonext) {
var f = document.getElementById('file_form');
f.gonext.value = gonext;
alert(gonext);
f.submit();
}
Please note that there are other variables included in this function. gonext is not the only one, but I am leaving the others out in this case to keep it simple.
My HTML for simplicity sake looks like this:
<form name="file_form" id=file_form action="<?= $this->URL('#', 'UpdateUploadUser', array('mode'=>'upload', 'ID'=>$_GET['ID']));?>" method="post" enctype="multipart/form-data">
<input type="text" name="oneitem">
<button name="submit1" id="submit1" onclick="do_file_form_submit(2);"><img src="<?=$theme;?>/images/12addphoto32px.png">Save Settings Then Upload/Register Another</button>
On the backend side within the "UpdateUploadUser" function we have a checker which checks each submitted field to see if it is empty or not. If it is empty, it returns:
$this->chk = new mVal($event);
if(!$this->chk->Validate()) {
$this->mode = 'error_redisplay';
//$this->mode='Error';
return;
}
If all info is there, then the script continues and runs as expected. So, here is the issue.
If all information is there, and I click the button, then all works fine. The file_form submit JS ALERTS the gonext value and the script runs and updates as it should.
HOWEVER, if an item is missing, then the validation script runs and "RETURNS".
Once the page has been returned, if you THEN attempt to click the submit button, the page STILL submits as it should, but the file_form submit script seems as if it doesn't even run, so that the gonext value is not passed at all.
So, I am trying to figure out how the submission of the form is still happening apart from this do_file_form_submit script. Is there something having to do with "return" that I don't know about?
Hope that makes sense and thanks for any help!
Craig
Review your code
function do_file_form_submit(gonext) {
var f = document.getElementById('file_form');
f.gonext.value = gonext;//f.gonext. i can not find gonext in ur form. just oneitem try something like f.oneitem.value = gonext; i believe that is where the //problem occurs
alert(gonext);
f.submit();
}
in nutshell, replace the line:
f.gonext.value = gonext;
with
document.file_form.value = gonext;
and then submit like
document.file_form.submit();
Related
As part of my new job, I'm creating a small form where users answer a question and this is then saved and output at the end of the pages.
I started off with having a prompt where users were asked to explain their answers (which worked perfectly!), however I've been asked to change this to an input box.
Essentially the process I need to do is:
User enters in text box -> Clicks next button -> save input to session variable and move to next page
So far, I have the following HTML in the body:
<form name="next" action='#' method=post>
Explanation:<input type="text" id="xp" required><br>
<button class="nextButton" onclick="return explanation()">Next</button>
</form>
with the corresponding javascript:
function explanation() {
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
document.location.href = 'page2.html';
}
So far the result of this is:
The text box is cleared, but nothing is saved or displayed onscreen
The next page is not displayed.
Any help/advice would be appreciated. I'm relatively new to js so I'd be grateful! I'm well aware that there are similar questions around, I just can't seem to see where I'm going wrong.
#David is right. You can add event.preventDefault() function to prevent the form from its default behaviour, which is submitting. Otherwise your code seems to work.
function explanation() {
event.preventDefault(); // <-- add here
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
window.location.href = 'page2.html';
}
Also, don't use document.location.href, it's deprecated. It's better to use window.location.href instead.
When you click on nextButton, the browser run explanation() and then try to execute the action of your form. Because your action is action='#' it just try to reload the page, preventing document.location.href for working properly.
Actually, you can try to don't enter nothing on the box and click on the button. The redirect will work because the form is empty, so there is nothing to submit.
I'm creating a website game and currently I am struggling with something I will name "dialogue".
Initially I tried to approach this by creating a form element, but clicking enter or submitting it ended up with page refresh, which ruins everything.
So I used inpute type text without form that looks like this:
You are
<input type="text" id="dead">
<input type="submit" onclick="dead()">
and dead function looking currently like this, later it's gonna check for certain value, and if the value is true it's gonna run another code:
var talk = document.getElementById("dead").value;
function dead() {
alert(talk);
}
And I don't know how to save input from a form so it would be detected by JS and then used as variable in boolean check. How can I solve this problem? If there is a way to use a form tag without refreshing the page that could also work.
You can handle the submit event of your form like this:
document.getElementById('yourFormId').onsubmit = function(e) {
// your code goes here...
e.preventDefault(); // this will prevent the default operation of your form within this event
return false;
}
Or create a function:
function handleForm(e) {
// your code goes here...
e.preventDefault();
return false;
}
And add this to your form tag:
<form onsubmit="return handleForm(this);">
To be able sending some value without refresh the page you can use Asynchronous JavaScript + XML (AJAX) and if you're working with pure Javascript without some frameworks you can see a good documentation about Ajax.
But of course I suggest to use some frameworks like Jquery to make your works more easier
I have a form called signup. I decided rather than having a button, I would have text with the use of JavaScript to submit, however the form is not submitting.
Finished
First, you should separate your Javascript from your HTML. Read More
You should post more code e.g. HTML.
Here's a working example to get a form to submit:
HTML:
<form id="signup">
</form>
<a class="submit" href="#">Submit</a>
Javascript
var form = document.querySelector('#signup');
var submitBtn = document.querySelector('a.submit');
submitBtn.addEventListener('click', function() {
form.submit();
})
https://jsfiddle.net/hpg6mnnr/
I think you can achieve what you are looking for with this
Finished
You could try achieving your objective using the javascript onclick event handler. Let me explain it to you with the help of an example, as below
<html>
<body>
Google
<script>
function f1() {
alert("f1 called");
//function f1()'s alert demonstrating additional functionality
}
window.onload = function() {
document.getElementById("link").onclick = function fun() {
alert("hello");
f1();
//executing an initial "hello" alert
}
}
</script>
</body>
</html>
Here we create a link and give it an ID of link. Suppose we need it to execute some functionality when it's clicked. All fine for now.
Now after the document is loaded (as demonstrated by window.onload) we wait for the link to be clicked. If it's clicked, we execute the onclick event which gives an alert "Hello". Further suppose you wanted to execute some extra functionality with the click of your link (like submission of a form, as in your case), so we demonstrate it here using the f1() method. As you might see we execute all of these simultaneously simply by using the onclick event handler.
Well, you have several ways to do it!
Firstly verify if there is not another HTML element with the same id as you form, because if it has, you have two problems, one your HTML is not well formatted, second it may be defined first than the tag and of course, the document.getElementById('signup') will catch it firstly. Also if the page hasn't been loaded by complete, it won't find the element, try (see form down below):
window.onload = function () {
var aBtn = document.getElementById('myA');
aBtn.onclick = function () {
document.getElementById('submit').submit();
}
}
Another reason but less probable is, your active scripting (javascript for example) may be disable.
Verify it just in case:
Internet Options -> Security Tab -> Custom Level -> Scripting -> Active Scripting -> [Enable]
I've just copied your code and it worked for me.
E.g.:
<form id="signup" action="http://google.com">
go
</form>
You also can use onclick="document.getElementById('signup').submit();" or go with a button or input type="submit"
E.g.:
<form id="signup" action="http://google.com">
go
<input type="submit" value="go2">
<button>go3</button>
</form>
Well, there is other ways to do it but I think those are enough!
I have this HTML form
<form name="nextform" action="anotherpage.php" method="post" enctype="multipart/form-data">
<input name="pinid" id="pinid" type="hidden">
<input type="submit" name="submit" id="post" value="Lets Go" class="formButtonMap">
</form>
pinid dynamically gets a value using JavaScript. When it gets a value I alert it and it works.
But, when I click the Lets Go button, nothing happens. I see the Internet Explorer loading for a couple of minutes and then I get the message “The webpage does not respond”. If I hit refresh it goes to anotherpage.php but the values from the form did not arrive to the server.
Rarely shows this message:
Visual Studio Just-In-Time Debugger
An unhandled win32 exception occured in iexplorer.exe [688]
Possible Debuggers :
New Instance of Microsoft Visual Studio 2012
This behavior is observed only in Internet Explorer 11.0.2. The form works in older versions of Internet Explorer and also in Chrome and Firefox. I get no errors in IE’s console.
Here is the JavaScript code, placed above the form:
// called when another button is clicked - basicaly is websockets
function save() {
var so = new WebSocket("ws://localhost:8000");
so.onerror = function (evt) {
alert('problem');
}
if (sara == 'LINES') {
so.onopen = function() {
so.send(JSON.stringify({
command: 'insertAll',
name: document.getElementById('name').value
}));
}
}
if (sara == 'POLY') {
so.onopen = function() {
so.send(JSON.stringify({
command: 'insertHalf',
name: document.getElementById('name').value
}));
}
}
so.onmessage = function (evt) {
var received_msg = evt.data;
document.getElementById("next").style.display = "block";
document.getElementById("name").value = "";
document.getElementById("descr").value = "";
clearLinks();
document.getElementById("pinid").value = received_msg;
alert(document.getElementById("pinid").value); // works
so.close();
}
}
I tried to edit the code using document.getElementById("nextform").submit();, problem is still there.
Is it me? Is it a bug? What am I missing?
I believe this is a bug when setting form values to empty in IE.
IE Bug Report
I would suggest trying a different method to resetting the form values, I have used this method in the past:
document.getElementById('name').parentNode.innerHTML = '';
Maybe not your issue, but:
<input type="submit" name="submit" ... >
Giving a form control a name of submit will replace the form's submit method with a reference to the control, so calling form.submit() will attempt to "call" the input.
hi might be problem in your code you miss to add id in form and you try to access form by it's id that you not define.
document.getElementById("nextform").submit();
its required
<form name="nextform" id="nextform" action="anotherpage.php" method="post" enctype="multipart/form-data">
...
...
...
</form>
Trace through what happens in the anotherpage.php page when it receives the postback, evt.data might not be encoded as you expect (is it binary or text, if text, is it utf-8).
Postback to a different page where all it does is output the posted back values.
Does the socket close throw an exception?
so.close();
My original code has a form with more than 5 fields. When submitted calls the save(). save() function also clears the fields using JS.
There is a bug in IE11, that crashes the browser if you try to clear more than 5 fields , using JS. See here , there is workaround.
That bug crashes the first form, then the nextform form and also the browser. I APOLOGISE for not posting all my code, I did not know it had to do with the first form.
Because I thought the same piece of code had two different problems , I posted another question, very similar , here
In my case the input button had the same ID and NAME. So you can check if they are the same and if indeed they are the same use different value for one of the parameters.
I hope it helps.
I have HTML two forms, one that submits data upon entry to a database using PHP, the other directs the user to a paypal payment page, my problem is that the user would have to submit both forms which of course I do not want them to have to do. Is there anyway to use one submit button for two forms?
(Javascript is welcome)
You should be able to do this with JavaScript:
<input type="button" value="Click Me!" onclick="submitForms()" />
If your forms have IDs:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
If your forms don't have IDs but have names:
submitForms = function(){
document.forms["form1"].submit();
document.forms["form2"].submit();
}
A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:
var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));
document.forms.payPal.submit();
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)
If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.
I recommend you use/generate a single request which you can transact server-side.
The currently chosen best answer is too fuzzy to be reliable.
This feels to me like a fairly safe way to do it:
(Javascript: using jQuery to write it simpler)
$('#form1').submit(doubleSubmit);
function doubleSubmit(e1) {
e1.preventDefault();
e1.stopPropagation();
var post_form1 = $.post($(this).action, $(this).serialize());
post_form1.done(function(result) {
// would be nice to show some feedback about the first result here
$('#form2').submit();
});
};
Post the first form without changing page, wait for the process to complete. Then post the second form.
The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).
I didn't test the code, though.
If you have a regular submit button, you could add an onclick event to it that does the follow:
document.getElementById('otherForm').submit();
if you want to submit two forms with one button you need to do this:
1- use setTimeout()
2- allow show pop up
<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);
}
</script>
<form target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>
javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.
edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.