Working form without action - javascript

I'm trying to do html form without action. It must:
1) Remember input data as normal form do.
2) Doesn't reload page
I tried:
<form action="javascript:void(0);" id="simple-form">
But on
$('#simple-form').submit();
form didn't remember input data.
Normal form
<form action="#" id="simple-form">
reloads page but also remembers input data.
Does exist another way to remember data without forms with javascript?
Update #1:
event.preventDefault(); // onsubmit event prevert
Doesn't work same because it's preventing not only reload of page but also saving of data (autocomplete).

With javascript
var form = document.getElementById("simple-form")
form.onsubmit = function (event) { event.preventDefault() }
if(localStorage){
var textfield = document.getElementById("yourTextfield");
var data = localStorage.getItem("yourTextfield");
if(data){
textfield.value = JSON.parse(data);
}
textfield.onkeydown = function(){
localStorage.setItem("yourTextfield",JSON.stringify(textfield.value));
}
}
ok alternative solution with history object
var data = history.state.textfieldName;
if(data){
textfield.value = data;
}
textfield.onkeydown = function(){
history.state.textfieldName = textfield.value;
}

Related

HTML form reset after AJAX submit

I have a simple HTML form, with reset and submit buttons, which is submitted using an AJAX call.
Before any submit, the reset button is restoring form's initial state and I'm OK with that!
Buf after submitting the form, if I modify input values, I would like the reset button to restore form's state as it was after the last successful submission!
Is there any way to do this without reloading or recreating the form?
Best regards,
Thierry
It depends how you are submitting the form, but in general, with ajax, there is no kind of redirect, so the only question is removing the currently entered data to its default value.
Simple, at the start of the form loading (possibly at page load, but if its being generated after somehow, then right after its made), simply loop through the elements of the form and keep track of the values and store it to some kind of dictionary or array, then, after the ajax is submitted, reloop through the form and reset the values to the other corresponding values from before.
For example, if I had a form with an ID of "testForm"
let list = Array.apply(0, testForm.elements).map(x=>({name:x.name, value:x.value}))
...do ajax stuff, then after submitting the form:
Array.apply(0, testForm.elements).forEach((x, i) => {
x.name = list[i].name;
x.value = list[i].value
});
should reset it to the default values.. Possibly resetting the name is unnecessary, but its possible it was changed theoretically..
The main idea - save state
const input = document.getElementById("name");
const reset = document.getElementById("btn-reset");
const save = document.getElementById("btn-save");
const state = {
name: ''
};
save.addEventListener('click', () => {
// send AJAX
const value = input.value;
setTimeout(() => {
const serverResponse = {name: value};
state.name = serverResponse.name;
}, 1000)
});
reset.addEventListener('click', () => {
input.value = state.name
});
<input id="name" value="">
<button id="btn-reset">Reset</button>
<button id="btn-save">Save</button>

Question about <form onsubmit "function() ">

i have wrote a function to activate onsubmit"" in the form.
In the function(JavaScript) i try to fill variables with input from the fieldset.
On troubleshooting i immediately found out that all the input gets cleared before i can save them into the variables.
I know that this is not how forms are used but i do like how it points out the fields that still needs to be filled.
so is there a way or someone how figured out a way to outsmart the submit to do something(function) before the refresh? or is there absolutely no way?
function objectfill() {
var vnaam = document.getElementById('Voornaam').value;
var anaam = document.getElementById('naam').value;
var mail = document.getElementById('email').value;
var tele = document.getElementById('mobiel').value;
var rknr = document.getElementById('rijksregister').value;
var actie = document.getElementById('workshop').value
var k = document.getElementsByName('Room');
var room
for (var i = 0; i < k.length; i++) {
if (k[i].checked) {
room = k[i].value;
}
}
var personeel = new personeelgegevens(pnr, vnaam, anaam, mail, tele, rknr,
actie, room);
console.log(personeel)
This was the function i used onsubmit="objectfill()"
I wanted to fill the object but obviously not working.
You just need to prevent that submit from happening so that your JavaScript can run, by calling event.preventDefault(). Also, try using element.addEventListener() instead of inline event properties.
// Assuming a form that looks like
<form id="myform">
// Do
const form = document.getElementById('form')
form.addEventListener('submit', event => {
// prevent the form from submitting
event.preventDefault()
// The rest of your form code here
})

How to remember form data that has not been submitted?

How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});

Change values in form submitted and the JQuery serialize function

Please look at the following code. When the form gets submitted, is it actually submitting the values I have entered i.e. val(50) or at the point it serialzies does it just get data from the form on the actual html page?
// stop all forms from submitting and submit the real (hidden) form#order
$('form:not(#order)').submit(function(event) {
alert($(this).attr('id'));
//event.preventDefault();
if($(this).attr('id')==='quick2a'){
alert('quick2a being submitted');
//submitQuick2a();
$('form#order input[name=custom_channels]').val(50);
var name = 'het-';
name += $('form#order input[name=platform]').val('astsk');
name += '-ga-';
name += $('form#order input[name=license]').val('floating');
$('form#order input[name=productname]').val(name);
$.post('/store/cart/add/ajax/', $('form#order').serialize(), function() {
document.location.href = '/store/checkout';
});
}else{
//
}
I want those values to be set in the form regardless of what is set by the user, am I doing this correctly?
Thanks all
Why not just construct the data directly instead of stuffing it into a form and then grabbing the values via serialize?
$('form').submit(function(event) {
if($(this).attr('id')==='quick2a') {
var data = {
'custom_channels': 50,
'platform' : 'astsk',
'license' : 'floating',
'productname' : 'het-astsk-ga-floating'
};
$.post('/store/cart/add/ajax/', data, function() {
document.location.href = '/store/checkout';
});
}else{
//
}
return false;
});
It gets the values from the HTML page... but by calling .val(...) you're setting the values on the HTML page, so your code will work as you want it to.

setting action of form with javascript wont work

Im trying to set the action of a form with javascript!
How come it wont work on this code: (what happens is that the page gets submitted to itself, as in 'action="#"'
function validateForm() {
var nr_of_pics=document.getElementById("annonsera_nr_pics").value;
var name = document.getElementById("annonsera_name");
var tel = document.getElementById("annonsera_tel");
var email = document.getElementById("annonsera_email");
var area = document.getElementById("annonsera_area");
var community = document.getElementById("annonsera_area_community");
var category = document.getElementById("annonsera_category");
var subcats = document.getElementById("annonsera_subcats").getElementsByTagName("select");
var headline = document.getElementById("annonsera_headline");
var description = document.getElementById("annonsera_des");
var price = document.getElementById("annonsera_price");
if (nameValid(name) && telValid(tel) && emailValid(email) && areaValid(area) && communityValid(community) && categoryValid(category) && subcatsValid(subcats) && headlineValid(headline) && descriptionValid(description) && priceValid(price)){
var form = document.getElementById("annonsera").action;
form = "bincgi/verify_"+category+".php";
alert (form);
return true;
}
return false;
}
and the form:
<form name="annonsera" id="annonsera" method="post" enctype="multipart/form-data" onSubmit="return validateForm();">
BY the way, the alert box wont show up either!
ALSO, setting the form action manually in HTML works fine, and the form is validated properly!
var form = document.getElementById("annonsera").action;
form = "bincgi/verify_"+category+".php";
These lines aren't doing what you seem the think they're doing.
The first line is creating a variable called 'form', and copying the form's current action into that variable as a string. The second line then sets the variable to a new value, but the form's action isn't being changed because the variable only contained a copy of the form's action.
This would be what you're after:
var formElement = document.getElementById("annonsera");
formElement.action = "bincgi/verify_"+category+".php";
However, I don't know why your alert box isn't showing up at all. Are you certain that all the validity methods are actually being passed?
Try this:
document.getElementById("annonsera").action = "bincgi/verify_"+category+".php";
The problem with your code is that you first read the action attribute into a variable:
var form = document.getElementById("annonsera").action;
and then you set the form variable to a new string but this won't update the value of the DOM element.
Give it simple like
document.annonsera.action = "bincgi/verify_"+category+".php"
and to Submit the form
document.annonsera.submit()

Categories