I have two form elements; a SELECT drop down list which serves as an input for a javascript function, and a TEXTAREA which also is an input to the same javascript function. The textarea input needs to be submitted to PHP on the server more or less simultaneously with its use by the local javascript. Ideally, both the javascript function and the $_POST submission to the server would be triggered by the same button click, but I have not been able to get this to work because use of the textarea input by the javascript function prevents it being submitted to the server and vice versa (both these actions need the same data apparently causing interference. I have successfully worked around this problem by triggering the DOM submit() to the server with an onmouseout attribute on the input button.
The problem I now have is that the page refreshes wiping away the input values when the textarea input is submitted to the server. I don't want this to happen: I want the selection from the dropdown list to remain selected, and the text that was input to the textarea to remain in the textarea to ramain after submission. I have tried with the elements inside FORM tags and outside - page gets refreshed wiping away the values either way. There are many similar questions and suggested solutions posted on StackExchange, but after spending many hours trying many of them, I have yet to find one that works for me. Basically, they fall into to categories: ones that prevent the submit such as preventDefault and return false, and ones that don't prevent the refresh or don't work at all such as various javascript/jquery submit methods. To me, such submit methods beg the question of how does the server know anything about the method used to send the submit (other than whether it is GET or POST)? Doesn't the php code on the server receive the same $_POST array regardless of the method used to send it? How would it know the difference between an html form submit, a DOM submit or a javascript/jquery submit? It is not surprising that they all trigger the same page refresh in response.
It seems like there surely should be some simple way to retain the form values after submit because surely there are many times one would want to do this.
P.S. I am no fan of jquery, I found ajax to be much easier before jquery was created. That said, at this point I would appreciate anything that works. I have almost no familiarity with jquery so please, for any responses that use jquery, please give an example of how it would be implemented in my case (where it would be placed and how it would be triggered).
PreventDefault, return false, all manner of javascript and jquery submits, removing the FORM tags, sending the return to a hidden iframe
<select id="thisselection" class="sameline"><option selected>Select this</option></select>
<script>
function sendTextarea() {
document.getElementById("pform").submit();
}
</script>
<form action="" name="pform" id="pform" method="post">
<textarea id="text" class="sendbox" name="text" cols="45" rows="10">Hello world</textarea>
</form>
<input type="button" value="Send" id="pform" onclick="myFunction.speak($('#text').val(),$('#thisselection').val());" onmouseout= "sendTextarea();"
/>
Everything works OK but I have not found a way to send the textarea input to the server without triggering a page refresh.
I wish I could simply prevent the page refresh, but lacking a means to do so, it is possible to save and restore the form values after submit (as suggested by ADyson. There is something in html5 called localStorage or sessionStorage, and there are ready-made scripts that make it easy to use, including savy.js and formsaver.js There are several of them at https://www.jqueryscript.net/tags.php?/localStorage/ savy.js works for my purpose
Related
The problem is quite simple to understand but quite hard to execute. I am currently facing some clients that turn off their browser Javascript by default and this screw up my website a bit. Since my website send ajax requests on form submit, stop the form submit using Javascript, turning JS off means the form will be sent through and that's unexpectedly.
What I am trying to ask and achieve is whether it is possible to just using html purely to stop a form from submitting?
I think the best answer is; to have the original form action point to an error page, asking the user to turn on javascript.
Then let your javascript code fill in the form action parameter, once the ajax state is complete.
Alternatively or additionally, you could use a <noscript> tag as suggested in the comments, to generate a message on the original page.
I think you can simply change your submit button tag to an input and style it to look like a button and remove the type="submit" that's all. with out ajax it will not respond.
This is my first time using HTML/CSS to create a form:
While trying to switch from google form to html form for the sake of having an upload button, I've found this very useful answer: Upload file/stackover
Then I looked at improving the design, so I'v found this:
CSS HTML Form Designs Template; (I've used Form Style 10).
So after trying and trying I've managed to do this:
JSFIDDLE
the Thanks.html file is missing (as on the original example post)
I'm almost done except few thing to sort out, if anyone can help me out that will be great:
I'd like all the required values to be checked upon submission
I've tried to add required Name: <input type="text" name="name" required /> nevertheless it sends the form data to the spreadsheet then display error message in the 1st required field (basically I'd like nothing to be sent until everything is ok in the form) (I read few things about onclick/onsubmit and type="button or submit"
but couldn't sort it out)
in the Thanks file, I've removed everything and wrote only:
<div>
<p><blink>Thank you <?= name ?>, your application has been received.</blink></p>
</div>
How can I center this message under the form, increase size and change colour to red please
I've tried to add the inner-wrap (grey colour around fields) as the template (Form Style 10) by adding: <inner-wrap> instead, but it doesn't work (any idea?)
Thanks you for your help
The reason why it doesn't do what you want is because the button still submits and you have no preventDefault event on submit because they assume you handle it on the backend. But will still display error messages to let the user know something is wrong.
There are several ways you can attack this problem:
you could use a 3rd party plugin like jquery validate
you can handle it to not submit until you check all the fields and then call
form.submit() (via this method you have the final one on the bottom not be input with type='submit' and handle click event and call a validate form method then submit if everything is alright)
on the backend you can check the fields to make sure they're all filled out and not even save to whereever
as for your text-centering: https://developer.mozilla.org/en-US/docs/Web/CSS/text-align
Edit:
For form validation, import the jQuery Validate at the top of your page either with the CDN/local js file and then call:
$("#commentForm").validate();
So I'm working on a chat system and even though I know it works in a pretty lame way - submitting messages in a new window () - I'm interested if there's any way to reset the textarea's content after sending the message.
Now, the problem is, I've even actually found ways to do so via JavaScript (editing the textarea's value), but I don't know how to "launch" the javascript after submitting the form.
Obviously, I can just use onSubmit(), but that delete's the value BEFORE sending the data. So it works, but sends an empty text.
Any ideas?
Thanks!
A common solution is to copy the values of your <form> into an object which you can then convert to JSON. That way, you have a copy of the values which doesn't change when you reset the fields of the form. jQuery will make this very simple. See also: serializing and submitting a form with jQuery POST and php
The second solution is to submit the form and as the last thing, add a timeout which resets the form. But there will be a small gap and a user might be able to type while your handler is clearing the form.
Okay, so I've used a JavaScript timer to run the clearing function 300 ms after clicking the submit button. Works. Thanks all :)
I have the following code on my Home.aspx page:
<form id="frmJump" method="post" action="Views/ViewsHome.aspx">
<input name="JumpProject" /><input type="submit" value="Go" />
</form>
However, when I click the "Go" button, the page posts back to Home.aspx rather than going to ViewsHome.aspx.
I even tried adding some script to force the form to submit:
<input name="JumpProject" onkeypress="if(event.keyCode == 13) { this.form.submit(); return false; }" />
But still even if I press ENTER, the Home.aspx page is reloaded.
The only thing I can see that might be borking things is this form is actually a child form of the main POSTBACK form that ASP.NET injects into the page.
I'm sure there's something stupid I'm missing and this post will get 800 downvotes instantly banishing me back into the n00b realm, but perhaps I haven't gotten enough sleep lately and I'm missing something stupid.
This is on IE7 and an ASP.NET 4.0 backend. I also have jQuery libraries loaded on the page incase jQuery can improve this somehow. Thanks!
The most simple explanation is that forms cannot be nested.
You might consider revising your submit logic to appropriately handle the scenario server side (via the single postback form.) Otherwise you might have to consider a route that deviates from the standards ASP.NET Webforms postback model.
You can't nest forms in HTML, so the browser will ignore the inner form tag. When you submit the form, it will submit the only form that is on the page.
If you need to post a form to a different page, you can use Javascript to either change the current form before it's sent (onclick on the button), or create a new form element, add it to the page and submit that instead.
You're not allowed to nest forms in HTML. It's not supported by most browsers anyway.
What you can do instead, since you're suffering through .net webforms, is to just have a Button_Click event in the C# corresponding to the submit button you're clicking, and have it do the project jump from there.
I have a form with an array of text fields. The user (through javascript) can add an arbitrary number of text fields to the form. After submitting the form and pressing the back button the form displays only with the fields that were on the original form when it was first rendered (any added text fields are lost). What is the best way to allow the back button to render the form in the state when the user submitted it? Any ideas are welcome, some things I've tried are:
Put the form data in a cookie (this
doesn't work great for a couple
reasons but the biggest killer for me
is that cookies are limited to 4K in
size)
Put the form data in a session
Submit the form via AJAX and then manage the history
Thanks for the help. I've posted a test form on my website at http://fishtale.org/formtest/f1.php. Also here is a simple form exhibiting the behavior I mentioned:
<form action="f2.php" method="post">
<input type="text" name="text[]" id="text1"/>
<input type="submit" name="saveaction" value="submit form" />
</form>
Add Form Element
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" ></script>
<script type="text/javascript" >
$('#add_element').click(function (event) {
event.preventDefault();
$('#text1').after('<input type="text" name="text[]" />');
});
</script>
This is similar to a question I posted a while ago, Best Way For Back Button To Leave Form Data, however, this form's elements are modified by the user.
How about creating an <input type="hidden"> (with no name or outside the form so it's not submitted) in which you store an encoded list of extra fields to add and their values? While the browser won't remember newly-added fields on ‘back’, it will remember the values of hidden fields that were in the form from the start.
Here's an example that saves the extra fields on document unload and retrieves them on ready:
<input type="hidden" id="remembertexts" />
<form action="http://www.google.com/" method="get">
<div id="texts">
<input type="text" name="text[]" value="" />
</div>
<div>
<input type="submit" />
<input type="button" id="addtext" value="+" />
</div>
</form>
<script type="text/javascript">
// Add new field on button press
//
$('#addtext').click(function() {
addInput('');
});
function addInput(text) {
$('#texts input').eq(0).clone().val(text).appendTo('#texts');
};
// Store dynamic values in hidden field on leaving
//
$(window).bind('beforeunload', function() {
var vals= [];
$('#texts input').each(function() {
vals.push(encodeURIComponent(this.value));
});
$('#remembertexts').val(vals.join(';'));
});
// Retrieve dynamic values on returning to page
//
$(function() {
var extratexts= $('#remembertexts').val().split(';').slice(1);
$.each(extratexts, function() {
addInput(decodeURIComponent(this));
});
});
</script>
Notes:
You can use form.onsubmit instead of window.onbeforeunload if you only need it to remember values over a submission. onunload doesn't work as some browsers will already have stored the old form values before that event occurs.
In Firefox the position of the hidden input is important. For some reason, if you put it below the dynamically-added fields, Firefox gets confused about which input it is and fails to remember the value.
This example doesn't work in Opera. It can be made to work in Opera, but it's a pain. Opera's calling of load and unload events is inconsistent so you have to use onsubmit instead, or setting the hidden field on a polling interval, or something. Worse, when Opera remembers previous form-field values, it actually doesn't fill them in until after onload has fired! This already causes many, many form-scripting problems. You can work around that by putting a small timeout in your onload to wait until the form values have gone in if you need Opera compatibility.
I can't find a prewritten library for this, but I'm sure its been solved before. If I had to it myself I would take this approach:
Use the command pattern so that each method which modifies the page's UI by adding controls also invokes an AJAX method to push the method invoked (textual Javascript representation) onto a queue stored in the server's session.
After body onLoad completes, use an AJAX method to query the server's session for a command queue for the page the user is on. If one is retrieved, just eval each member of the queue to rebuild the page's UI in the same order the user did it.
Keep in mind with this approach you are recording not just additions of controls, but removals as well. You will require separate state holders for user input controls, like text boxes (you will also likely need server-side session with AJAX method access).
In good browsers you can have it working perfectly simply by not breaking it.
Firefox 1.5 uses in-memory caching for entire Web pages, including their JavaScript states, for a single browser session. Going backward and forward between visited pages requires no page loading and the JavaScript states are preserved. source
This is supported in Opera and WebKit too. However DOM cache is only possible in you stick to the rules:
Don't use onunload, onbeforeunload.
Don't use Cache-control: no-store or must-revalidate.
In PHP you must change session.cache_limiter from patently_ridiculous (I think they spell it nocache) to none.
session_cache_limiter('none');
Unfortunately HTTPS is also out.
If you don't force browsers to reload the page, they won't. They'll keep the DOM and its values unchanged, exactly as RFC 2616 suggests.
However, if you're looking for place to stash the data, there's incredibly clever hack – window.name can store megabytes of data. It's not sent to server, and it isn't shared between windows.
There are also Flash cookies and HTML 5 localStorage is implemented in IE8 and Safari 4.
Step 2: The script processing the form puts the values entered into an array and stores that array into a session variable (or text / db / whatever you find appropriate).
Step 1: The script which outputs the form adds a javascript (which in turn fills in the form) if that session variable is found (and it also clears the session variable).
You could make your own back button at the top of the web page and make it bigger and prettier than the standard web browser back button.
Under the hood your code could know what the previous state was and revert to it or if there was no previous state you can maybe call the browser's back function?
Block the use of the back button. When the back button is pressed, rerender the previous page for the user with the new fields included, either visibly if that makes sense, or hidden. That way the user is able to use the back button normally and you have full control over the appearance of the ''previous'' page.
In your specific use case, you just need to render the page with all the fields visible and filled in with the values that were submitted.
This is a good pattern to follow for any wizard type of process where you provide a sequence of forms for the user to fill in and they may choose to go back to a previous form.
To make it perfectly clear, I am suggesting that you use this advice on capturing the onUnload event to trigger form submission (so that you get the entered values) and to rerender the previous page that "back" would have displayed (without the values). The only alternative is to use Ajax to send the entered values every time that the user leaves a field, and then have every page check with the server via AJAX to retrieve additional values to display.
Here are some additional pages that discuss taking control over the function of the back button and using the unload event to persist forms data:
Mastering the Back Button with Javascript
Don't Let the Door Hit You
Cross Browser unload Event and the Back Button
Persisting portlet forms data in WebSphere Portal V5.1