Disable browsers Form inputs prefill/autofill feature when hitting "back" button - html

I want to "prevent browsers from prefilling form inputs when hitting the "back" button". Indeed, I want the initial values to be filled in (added via jsp), not the browser's (cached) values.
Solution 1: I found out that this can be done by disabling the browser caching for the current page. This seems a rather extreme solution considering that I "only" want to disable this prefill feature for a "form" (hence disable caching for the form only, not the whole page).
Solution 2: Then, the obvious next solution is to use javascript: that is, store the initial value in a data-* attribute, then, on page load, replace the input value by the initial value if they differ.
Both solutions seem rather unperfect (these are rather work arounds) I turn to you guys hoping to hear of a better one.
Resources:
How does SO's form remember previous input values?
Disable Firefox's Auto-fill
Pressing back prefills inputs with value from right before submit
HTML form values and 'Back' button

The first thing that comes to my mind is to use a <input type="reset"> button. These aren't seen often nowadays because the user rarely actually wants to reset the form, but here it might just be what you need.
You could also do it in javascript on page load with form.reset(); instead of providing a button for the user.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.reset
This is similar to your solution 2 and thus still a workaround of the browser behavior, but it is a(n old) part of standard forms and I think it'll do the trick with very little additional code (no need for data-* attributes), so wanted to throw it out there.

Related

Using either GET or POST depending on submit button

I have a web application for tagging data and viewing data by tag, so my UI is a list of checkboxes for each tag, a list of checkboxes for each data item, a "Tag" button, which adds the checked tags to the checked data, and a "Filter" button, which ignores the checked data and just displays only the data items with the given tag.
My problem is that the former operation (tagging data) is "obviously" a POST operation, whereas the latter operation (viewing data according to a tag) is "obviously" a GET operation. But the method attribute is attached to the form, not the submit button, so I have to choose one or other for both buttons.
I don't want to make two forms, since as far as I can tell this would force me to duplicate the entire tag list. Is there any way I can choose my method based on the choice of submit button?
A JavaScript solution is permissible, but one without would be preferred.
(I am going to post an answer to this question, but I don't particularly like it, so I would welcome alternatives).
In principle, you could use the formmethod attribute in a submit button, as per HTML5. However, it is not recognized by IE, even in IE 9. The existence of the feature in HTML5 indirectly proves that previous versions of HTML lack a feature for this.
On the other hand, the POST method can be used even for simple viewing that does not cause any changes in the outside world, and in many situations it has to be used for technical reasons (e.g., too much data). So I think the method issue is not very relevant; just use POST.
I would honestly go with a javascript solution, in the onsubmit of the form fire a method which a) checks the submit button that was pressed and b) based on this changes the method of the form.
One possible solution would be to use POST, and then have the server give a 303 See Other header to change it into a GET request. This involves making two requests to serve the purpose of one, which is unfortunate, but at least means that the URL will change so people can link to a specific tag selection.
I agree with javascript solution, proposed by Jon Taylor, the problem is not if your form's method is GET or POST, but how do you filter/validate/sanitize user input. If your concern is related to the fact, that the user can manipulate the form's method, then you should implement solution to that matter on server side.

Clear all fields in a form upon going back with browser back button

I need a way to clear all the fields within a form when a user uses the browser back button. Right now, the browser remembers all the last values and displays them when you go back.
More clarification on why I need this
I've a disabled input field whose value is auto-generated using an algorithm to make it unique within a certain group of data. Once I've submitted the form and data is entered into the database, user should not be able to use the same value again to submit the same form. Hence I've disabled the input field in the first place. But if the user uses the browser back button, the browser remembers the last value and the same value is retained in the input field. Hence the user can submit the form with the same value again.
What I don't understand is what exactly happens when you press the browser back button. It seem like the entire page is retrieved from cache without ever contacting the server if the page size is within the browser cache limit. How do I ensure that the page is loaded from the server regardless of browser setting when you press the browser back button?
Another way without JavaScript is to use <form autocomplete="off"> to prevent the browser from re-filling the form with the last values.
See also this question
Tested this only with a single <input type="text"> inside the form, but works fine in current Chrome and Firefox, unfortunately not in IE10.
Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).
If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow and pagehide events:
window.addEventListener("pageshow", () => {
// update hidden input field
});
See more details for Gecko and WebKit implementations.
I came across this post while searching for a way to clear the entire form related to the BFCache (back/forward button cache) in Chrome.
In addition to what Sim supplied, my use case required that the details needed to be combined with Clear Form on Back Button?.
I found that the best way to do this is in allow the form to behave as it expects, and to trigger an event:
$(window).bind("pageshow", function() {
var form = $('form');
// let the browser natively reset defaults
form[0].reset();
});
If you are not handling the input events to generate an object in JavaScript, or something else for that matter, then you are done. However, if you are listening to the events, then at least in Chrome you need to trigger a change event yourself (or whatever event you care to handle, including a custom one):
form.find(':input').not(':button,:submit,:reset,:hidden').trigger('change');
That must be added after the reset to do any good.
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
This is what worked for me.
$(window).bind("pageshow", function() {
$("#id").val('');
$("#another_id").val('');
});
I initially had this in the $(document).ready section of my jquery, which also worked. However, I heard that not all browsers fire $(document).ready on hitting back button, so I took it out. I don't know the pros and cons of this approach, but I have tested on multiple browsers and on multiple devices, and no issues with this solution were found.
Because I have some complicated forms with some fields that are pre-fill by JS, clearing all fields is not suitable for me. So I found this solution, it detects the page was accessed by hitting the back/forward button and then does a page reload to get everything back to its original state. I think it will be useful to someone:
window.onpageshow = function(event) {
if (event.persisted || performance.getEntriesByType("navigation")[0].type === 'back_forward') {
location.reload();
}
};
As indicated in other answers setting autocomplete to "off" does the trick, but in php, what worked for me looks like this...
$form['select_state'] = array(
'#type' => 'select',
'#attributes' => array('autocomplete' =>'off'),
'#options' => $options_state,
'#default_value' => 'none');

Creating "are you sure?" popup window by using html only

Assume I have a html from, and it contain some submit type. I want to create a "are you sure" popup window that will appear when user click submit button.
My question is that is there any way to create it by using "only" html, not using javascript or any other?
HTML only is possible, but not without a postback
Scenario that could work without javascript:
You have your form with submit button
User clicks (and submits) the form
You display another form with are you sure? form (that contains Yes and No buttons as well as hidden fields of the first form that will make it possible to do the action required on the original data
functionality that executes the action and goes back to whatever required.
This would be completely Javascript free, but it would require several postbacks.
This kind of thing is usually done on the client with a Javascript confirm() function (here's a simple example) or lately with a more user friendly modal dialog provided by many different client libraries or their plugins.
When to choose the script free version?
If you know your clients are going to be very basic ones (ie. vast majority of your users will access your application using clients like Opera Mini that's not able to run scripts at all). But in all other cases it's much better to do this using Javascript. It will be faster, easier to develop and much more user friendly. Not to mention that it will put less strain on your server as well since certain parts will execute on the client without the need of any server processing.
No, there isn't. Despite of the new features in HTML 5, HTML is still a markup language, not a programming language. In order to express dynamic behavior (such as an "are you sure?" box), you need to use a programming language.
Javascript would be the most obvious choice for this, but you could also do it with frameworks that can get you around writing Javascript by hand (for example ASP.NET).
Edit: Actually it appears that it would theoretically possible to do this with without Javascript or other frameworks. As I just learned, HTML 5 + CSS 3 seems to be turing complete. But this is hardly relevant to this question.
It's possible to ask for a confirmation, but it will not be in a "popup window". The creation of the "popup window" requires javascript/other language.
It will be:
Request (first form)
POST
Response (confirmation form)
POST
Response (outcome message)
You can create a form with all hidden elements containing the data from the first form and a "Yes" and "No" button below the "Are you sure?" text. You can use PHP sessions to avoid the hidden form elements. If there is a lot of data or confidential data or you do not want to re-validate the data from the second form, use sessions. Make sure you validate the data from either form before using it.
I know I'm like .. 10 years late. But for anyone still wondering I thought I could be of some help!
What I did for this exact problem was make sure I had multiple "divs" in my code. For me specifically, I had two main ones.
First, one whose id="main", and another whose id="popup" with the 'visible' property initially set to 'false' for the popup div.
Then, on whichever event you're looking for (button click for example) you'll simply set main.Visible = false and popup.Visible = true, then you could have more buttons in your popup (yes, no, cancel, confirm, etc.) which do the exact same thing, but in reverse!
The most important thing to make sure of is that you have the 'runat="server"' property in your divs so that you can access them in your CS code
Hope this was helpful! :)

Chrome doesn't cache hidden form field values for use in browser history

I have a ASP.Net web form that contains both text box fields and hidden fields. The hidden field values are modified dynamically using client side JavaScript. Posting the form, inspecting the values and redirecting to another page is all working as expected.
However, when I use the browser back button to display the previous page then I expect so see that ALL form fields are still populated with the values that were posted.
In IE and Firefox this is the case for both text and hidden input fields.
In Chrome this is ONLY the case for text fields. The value of hidden fields is lost.
Is it true that Chrome never repopulates dynamically set hidden form field values when navigating the browser history?
I have put a small sample together to demonstrate the problem and can provide that if required. I wanted to first ask the question to see if this is well known behaviour and something I have to accept.
This problem could be solved using a small trick.
The problem is Form fields with Type=hidden with Dynamically set values are not handled properly by the Chrome Browser.
So the solution is to change the type of the field to text and use some other method to hide the visible text boxes. This could be achieved by surrounding all the text boxes carrying values intended to be hidden by a DEV tag pair and assigning the style as display: none
Then on the page you wont see the text boxes carrying hidden values and it will work properly with JavaScript of the browser.
BEFORE
<input type=hidden name=item_no value=00001>
AFTER
<div style="display: none">
<input type=text name=item_no value=00001>
</div>
You should not rely on this behavior. It is different among browsers, even among browser versions. This behavior is not described in any standards. If you want your fields to have specific values, you can use cookies, or always make requests to the server when page loads, or use more modern methods like local storage (it is not widely supported though).
I can't seem to comment, maybe my rep too low but felt this is important to mention.
I just ran into this problem myself in Opera so borrowed Sanesh Fernando's solution which worked around the hidden fields not being reinstated (Thanks Sanesh). However what caused a problem for me was that Javascript fires before the form fields are updated so if you check values with javascript as I was doing then I had to add a setTimeout to ensure Opera updated before I checked the values.
Cookies are as stated another way but what with the ridiculous EU directive on requiring cookie usage agreement from the visitor it's not a solution for me.

Do all browser's treat enter (key 13) the same inside form?

I have a form with multiple submit buttons, each of which is relevant to how the user wants the data saved and/or loaded.
The problem is (or was) that if a user pressed enter on the last (or any other) input within the form, the submit button that seemed to be called was the "load saved formed" which is at the top of the form. All attempts to user javascript to have the return button default to the "save form" seemed useless, almost as if the browser was too busy already submitting the form to have any js interfere.
Finally, in FireFox 3.5, I actually had the server-side script echo out what it received for the post variable and discovered that none of the submit button values were being passed back to the server. As it turns out, I have hooks in the script for when the user hits "Save" or "Save and Print", etc, but if the user uses the "load page" it simply updates a variable and continues loading the page normally with that variable in context.
So with no submit button value at all, it did the same thing, it simply loaded the page.
So, on to the big question:
Is this typical browser behavior? Maybe even reliable browser behavior? Will hitting enter always submit the form as though no submit button was pressed at all, or do some browsers like to pick a button to use as the default when the user presses enter?
If it is typical behavior, what is the suggested course of action? I was going to have the script save anything no matter what, so long as there was data in the form, but then I realized that this was even more dangerous, because if the user loads one saved form, changes there mind, and changes the form dates and hits "Load Form", then it will save the form data from the pervious form for the new dates they have requested.
I considered setting it up so that changing the load form inputs (selects with dates and other particulars) would clear the form so that the server still recieved an empty form and thus would not overwrite any previous data, but this is risky as well, as many users will certainly notice and think that their data has been lost, etc, and there is always the slight chance that the user will be almost done with the form, go up to the top and fiddle with the form-load selects just to confirm they chose the right what nots and then be forced to start from scratch.
I should just have two forms, one for loading, one for the data, but the problem with that is that all of the data in the load part of the form does get used by the main form. I could write more js to combine the two on submit, or hide the data in the second form, but all of that seems clunky.
Essentially, I need a setup such that the top part of the form is independent of the main form, but not vice versa. Submitting the upper form does not submit the lower, but submitting the lower does submit the higher.
Okay,I've gone on long enough. Basically I'm wondering if a solution already exists or if anyone else has run into this and found a clever fix. I thought simply having the form save whenever the form wasn't empty was pretty clever, until it occurred to me that when the user goes to the page, it auto-loads the most applicable form given the date, and thus changing the load variables will almost always caused trouble.
Having read the possible duplicate that Artelius was good enough to draw my attention to, I'm still unclear on the consistency across browsers regarding the Enter button as submit.
It seems that almost everyone in that question assumed that hitting enter presses the first available submit, which was also my assumption until a friend suggested I hide (via CSS) another submit button at the top of the form with whatever I wanted enter to achieve. It was when this got me the same results that I finally viewed what was being passed to the server (ie nothing in terms of a submit value). So that means either
a) the "enter as no submit button just submit" is new behavior for some or all browsers,
b) the "enter as just submit" vs "enter as first submit button" is just browser choice, no trends, just typical cross-browser unreliability, or
c) Everyone just keeps assuming that the "enter as first submit button" is the case because most of us only code if (situation1) else (assume not situation1) and none of us are really sure what the browser is doing.
I highly doubt it's that last one, but then again, I also highly doubt most of us know which browsers do which. I'd sure like it if there was a straight answer I could pass along.
Oh, and finally: While I know it would be far simpler to use buttons, and I am taking that under serious consideration, I would also like to consider other options, since really the only need for less submit buttons I have is for when users hit enter instead of one of the buttons.
Actually, let me get carried away one more second:
The only thing I really need to know is whether or not they hit enter FROM one of the text inputs. If I could pass that along to the server, I'd know if I should save or reload the form. But the problem is (or at least what I've had troubles with) is that when the user hits enter in an input, it seems like there isn't any more playtime with js to capture anything, and in some cases, it seems like the browser is triggering the onclick for whichever submit button and thus not really allowing me to know the real event that triggered that. I'll play around more with jquery, but has this behavior been observeed by anyone else?
My best advise would be to only have on submit button, and let that submit what ever is the most common usage of the form. Let the rest of the buttons just be normal buttons, which you can hook click events onto.
Just make sure you make it very clear which button will be "pressed" when the user hits enter. Let the submit button be the biggest one. If you have 3 buttons that are used equally as much, I would just drop having a submit button at all...
edit: I'm pretty sure most browsers will post all the data inside a form. If you want to do some checking on the data before posting you could add a listener for onsubmit
<form onsubmit="checkData(this);" ... >
Passing in this will let you check which form is actually being submitted:
function checkData(form) {
var formName = form.id;
//check all the data based on which form is being submitted
}
The HTML5 spec specifies synthetic click activation steps for implicit form submission:
A form element’s default button is the first Submit Button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.