Why select retain the value previously selected after reload [duplicate] - javascript

I have a big problem with the functionality in Firefox that keeps data that the user have filled in on reload F5. If i use Ctrl+F5 the forms are cleared and this is great. My problem is that not all my users know that this is what they have to do to force the input cleanup. Is there a way in the html or response headers to tell Firefox to not keep the data in the forms?

Just add autocomplete="off" to your inputs and you will solve the problem.
<input type="text" autocomplete="off">
jQuery to solve this on all inputs and textareas
$('input,textarea').attr('autocomplete', 'off');

Instead of going through all inputs you may also just add the attribute to your form-element like so:
<form method="post" autocomplete="off">...</form>
However the above mentioned methods on domReady did not work for me...

In case you want to keep the autocomplete feature of the browser (see other valid answers), try adding the name attribute to the form and give it a random value. It has worked for me:
<form id="my-form" name="<random-hash>">
...
</form>

/*reset form elements (firefox saves it)*/
function resetElements()
{
var inputs = document.querySelectorAll('input[type=text]');
//you get the idea.....you can retrieve all inputs by tag name input
for(var i = 0; i < inputs.length; i++) {
document.getElementsByTagName('input')[i].value = "";
}
var textareas = document.getElementsByTagName('textarea');
for(var i = 0; i < textareas.length; i++) {
document.getElementsByTagName('textarea')[i].value = "";
}
}
Call this function onload.

I think easier and quicker way to do that is
$('input,textarea').attr('autocomplete', 'off');

I tried the shortened solution above, but it didn't clear the value of the select boxes on my page.
I ended up modifying it slightly and now all input types on the page are cleared regardless of type:
var allInputs = $(":input");
$(allInputs).attr('autocomplete', 'off');
So to make this run onload I just put it in the ready() method:
$(document).ready(function () {
var allInputs = $(":input");
$(allInputs).attr('autocomplete', 'off');
});

I found the only fix for me was to do
document.forms[0].reset();
before doc ready early in the page, as suggested in the comment by #Marek above - not great but worked for me (the autocomplete attribute method via either jQuery, JS or HTML didn't in the end fix it for me)

just to piggyback on #jonnybradley's solution (couldn't comment on his answer because I don't have enough rep yet):
This also worked perfectly form me:
document.getElementById('theFormId').reset();
called after the HTML code.

one of my colleagues recommended that we should use a random string as the name of the form. It works very well if you don't use the name attribute of the form.
it is an example from the sf1 form builder:
public function renderFormTag($url, array $attributes = [])
{
..
$attributes['name'] = isset($attributes['name']) ? $attributes['name'] : bin2hex(random_bytes(16));
..
}

autocomplete="off" is also needed for hidden input fields in order to have them refreshed on simple page reload (F5)

Related

{"error": "Please use POST request"} - alternative solution to submitting a form

I'm working on a school project and have attempted to create a calculator that can be found at the following link:
http://jsfiddle.net/ae97vgxz/2/
And my JS is:
$(document).ready(function(){
// Setup variable as empty
var method = "";
// Detect when initial radio button is clicked
$("input[type=radio]").click(function() {
// Get the weight from the input box
var weight = $("#meatWeight").val();
// If the water method was clicked
if ($(this).hasClass("water")) {
var method = weight * 60;
// Show me what the value is (can be removed)
alert(method);
// If the fridge method was clicked
} else if ($(this).hasClass("fridge")) {
var method = weight * 793;
// Show me what the value is (can be removed)
alert(method);
}
});
When you use it, if you enter a weight first, then select a method of defrosting you will get the correct answer in an alert window. However, if you press the 'calculate' button you get the following message -
{"error": "Please use POST request"}
From doing some of my own research, I believe this is because I am trying to submit a form and JSFiddle doesn't let you do that. If I try on a local environment in Chrome, again there is no output.
I am very limited by my JS knowledge (as I'm sure you can see) so I just can't fathom out a solution. Can anyone suggest what I am doing wrong and what the solution might be?
Thanks!
You have a mistake here:
function defrost(weight) {
return (makeTime(method));
}
It should be:
function defrost(weight) {
return (makeTime(weight));
}
Also, you should change the makeTime function or it won't work. The parseInt clause should be like this:
parseInt(time / 60);
Your current method of submitting the form is GET
<form id="defrostCalculator" name="defrostCalculator" onsubmit="callbackDefrost(this.elements.meatWeight.value); return false;" method="GET">
If the destination requires POST, use POST.
<form ... method="POST">
Your code has a couple of minor issues. However, the major issue you have is that if you want to use a non-AJAX form on jsfiddle, you have to change all your buttons to have the attribute:
type="button"
instead of what you currently have:
type="submit"
When you do <input type="submit", jsfiddle.net squawks and fails because you cannot submit form information to their servers. Luckily, you do not need any AJAX or server interaction. So your simple calculator can just use simple buttons.

How to pass a user entered form value from html to javascript?

It is possible to pass a value from javascript to html by writing it to a tag. However, if I would wish to pass a user defined value (etc, entered by the person viewing the webpage) to java script so I can do things with it, what would be the most easiest way possible?
At the moment, I have something like this:
<div class="entry foreground-color">
<form>
<input type="text" name="commands" size="60"/>
</form>
</div>
How can I make the value from the form be passed to my javascript?
Or, am I going in a totally wrong direction? If so, what would be the correct way to get user input, and pass it on to javascript?
EDIT: Apologies for my misuse of terminology. I am making a text based adventure game, and I want the user to be able to type in a response, press enter, and have the response be sent to javascript, so I can use javascript to evaluate the response (etc "go south", "go north"), and write back to the element with the new situation (etc "as you went south, you found a troll").
You can just stop the form from submitting and get the value:
HTML:
<div class="entry foreground-color">
<form onsubmit="return getValue('commands')">
<input type="text" name="commands" size="60" id="commands"/>
</form>
</div>
JavaScript:
function getValue (id) {
text = document.getElementById(id).value; //value of the text input
alert(text);
return false;
}
Fiddle: Fiddle
If you want to clear the box afterwards, use:
document.getElementById(id).value = '';
Like so:
function getValue (id) {
text = document.getElementById(id).value; //value of the text input
alert(text);
document.getElementById(id).value = '';
return false;
}
The input value is already available for Javascript via DOM API:
document.getElementsByName( "commands" )[0].value
You can get the value of your input control using:
document.getElementsByName("commands")[0].value;
Since getElementsByName() method returns an Array of elements with specified name, you will need to take the first element assuming that there is only one elements with name attribute commands.
Instead of that, for simplicity and uniqueness, i suggest you use the famous way to achieve that using id attribute and getElementById() method.
<input type="text" name="commands" size="60" id="commands"/>
var input = document.getElementById("commands").value;
or
document.getElementsByName( "commands" )[0].value
now do anything with this
To get the value of an HTML element, first, you need to get the desired element (you can use theses methods):
getElementById
getElementsByTagName
getElementsByClassName
querySelector (moderns browsers)
querySelectorAll (moderns browsers)
Theses methods depending on document (documentation).
So in your case you can try something like this:
var inputs = document.getElementsByTagName('input'),
commandValue = null;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name === "commands") {
commandValue = inputs[i].value; // get the element value
}
}
alert (commandValue); // show the value
But you need to set a "catcher" on the form default action.
So:
<form>
Become:
<form onsubmit="return getValue()">
And you set the javascript code above in the getValue function:
function getValue() {
var inputs = document.getElementsByTagName('input'),
commandValue = null;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name === "commands") {
commandValue = inputs[i].value; // get the element value
}
}
alert (commandValue); // show the value
return false; // prevent default form action
};
You are in the right path :)
For example you can do something like this (see http://jsfiddle.net/ahLch/):
HTML:
<h1 id="commandsExample"></h1>
<div class="entry foreground-color">
<form>
<input type="text" id="commands" size="60"/>
</form>
</div>
JavaScript:
var input = document.getElementById('commands');
var example = document.getElementById('commandsExample');
input.addEventListener('change', function () {
example.innerHTML= input.value;
});
A couple of things to note:
If you are new to JavaScript, and you wish to make your code cross browser (especially if you want to target old versions of IE), take a look to jQuery.
If you wish to learn how to use plain DOM APIs provided by the browser without the jQuery layer, take a look to: http://youmightnotneedjquery.com/ (it's very useful once that you learned jQuery basics).
There are a couple of ways to get the value:
Intercepting from submmit event: I don't recommend it, you have to take care of avoiding the default submit behavior, and you have to create a form around your input field. That was necessary in old browsers, but today is not.
change event: it's fired when the input value has changed and the input looses the focus (is the usual event used for form validation).
keydown and keyup: they give you more control, by capturing each keystroke, but it's lower level than the change event. For a complete reference see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
Use "id" instead of "name". Name is only necessary when you want to submit the value, in new browsers you can leave just input tag without a form.
Getting the value of the input tag is quite easy with jQuery.
(I take it you need this anyway to actually send the message via AJAX to a server..?)
$("#idofinput").val(); will copy the value, $("#idofinput").val(''); will empty it.
You probably want to do this without actually submitting a form.
Recreating one in javascript isn't to hard.
For the submit on enter you can use something like this:
function checkEnter(e)
{
var keynum;
if(window.event) // IE8 and earlier
{
keynum = e.keyCode;
}
else if(e.which) // IE9/Firefox/Chrome/Opera/Safari
{
keynum = e.which;
}
if(keynum==13)
{
sendMessage();
}
}

How to enable a disabled text field?

I wanna know how do I enable a disabled form text field on submit. Also I wanna make sure if user goes back to form or click reset field will show again as disabled.
I tried to use
document.pizza.field07.disabled = false ;
It does disables the field, by clicking reset or hitting back button still keeps it enable.
Please guide.
To access this element in a more standard way, use document.getElementById with setAttribute
document.getElementById("field07").setAttribute("disabled", false);
EDIT
Based on your comment, it looks like field07 is a name, not an id. As such, this should be what you want:
var allfield7s = document.getElementsByName("field07");
for (var i = 0; i < allfield7s.length; i++)
allfield7s[i].setAttribute("disabled", false);
That is the only working solution for Me:
var allfield7s = document.getElementsByName("field07");
for (var i = 0; i < allfield7s.length; i++)
allfield7s[i].removeAttribute("disabled");
You can enable a disabled html control with the following JavaScript code.
document.getElementById('elementId').removeAttribute('disabled');
You can also do this with jQuery:
$(function(){
$("[name='field07']").prop("disabled", false);
});
We simply select all the elements where the name attribute is field07 (using name because you said so in the comments of #AdamRackis's answer) and set its disabled property to false.
More about prop().
You can enable a disabled html control(like, input, textarea, button,...) with the help following code.
To disable:
document.getElementById("id_name").setAttribute("disabled", true);
To enable:
document.getElementById('id_name').removeAttribute('disabled');

Clear default values using onsubmit

I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}

IE 6 and the multiple button elements all sending their name & values

When using multiple button elements in a form, I realised that IE7 sends the innerHTML instead of the value of the button. All good I thought, I'll simply change my PHP code to this
<?php
if (isset($_POST['button-name'])) {
add_product_to_cart(2);
}
?>
Now my old friend IE6 is going a little step further at being a nuisance. It sends all of the button elements regardless of which one I click. For example, I have 3 button elements named 'mint', 'near-mint' & 'standard'. A quick print_r($_POST) tells me that all 3 names have been submitted.
I guess to remedy this will be some JavaScript, not the most elegant situation, but I can imagine that the average user still using IE6 is not bright enough to turn off their JavaScript.
How can I remedy this?
I found a solution at http://www.codecomments.com/JavaScript/message756646.html
All credit to the author on that page.
Per request, here is the code
function buttonfix(){
var buttons = document.getElementsByTagName('button');
for (var i=0; i<buttons.length; i++) {
buttons[i].onclick = function () {
for(j=0; j<this.form.elements.length; j++)
if( this.form.elements[j].tagName == 'BUTTON' )
this.form.elements[j].disabled = true;
this.disabled=false;
}
}
}
window.attachEvent("onload", buttonfix);
This is a known bug in Internet Explorer.
http://www.dev-archive.net/articles/forms/multiple-submit-buttons.html describes a workaround that does not depend on JavaScript.
It boils down to "Use <input> and don't design your buttons to need anything other than simple text for their labels".
An solution is to use <input type="button"> and <input type="submit"> in your page instead of <button type="button"> and <button>.
Update: if you change your button elements to input elements you should be able to find them using jQuery with the following selector:
var buttons = $('input[type=submit], input[type=button]');

Categories