HTML form reset after AJAX submit - javascript

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>

Related

Store form in localstorage, retrieve it later for submit

In a wordpress website I want that when someone fills a product form (select attributes etc) and clicks buy now, if is not logged in then he is redirected to login form. On succesfull login I want to get the submitted form contents from localstorage, fill the form and then submit the form automatically.
Is that possible?
I found that I can store the submitted form like this (but how I can refill the form automatically?):
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
var formFields = $(this).serialize();
localStorage.setItem('myForm', formFields);
//data = localStorage.getItem('myForm'); //retrieve it later
});
});
You should be able to retrieve data from localStorage, get your form fields using DOM selectors and fill their values using the data from localStorage.
In vanilla JS, you can probably do the following:
document.addEventListener('load', () => {
// check if user is logged in according to your usecase
if(isLoggedIn()) {
try {
const formData = JSON.parse(localStorage.getItem('myForm'));
// get input fields. If you have some unique id associated to them, you can use document.querySelector(`#${inputId}`);
const inputFields = document.querySelectorAll('input');
for(let i = 0; i<inputFields.length; i++) {
const inputId = inputFields[i].getAttribute('data-id');
// fallback to empty string in case it is not found in localStorage object
inputFields[i].value = formData[inputId] || '';
}
} catch(e) {
// handle error
}
// Now you have the form input fields pre-filled, add custom logic from here ..
}
})
/*
--- Sample DOM ----
<input data-id="name" />
<input data-id="city" />
---- Form fields saved in localStorage ---
{ name : 'Naruto', city: 'Leaf Village' }
*/

Input validation does not trigger till I click something on page. How to avoid this?

I have inputs that I check for empty, null etc. I do this by storing a state boolean and updating it with onChange events for each input. Each input is stored in a session variable using React.useState. The validation work does work, but if I type something in then hit backspace till the input box is empty you can click submit button and send an empty piece of data and I do not know how to prevent this because I'm checking every onChange event for every input box.
Here is one of my inputs
<input id="editCourse_placeHolder_courseName" type="text" placeholder={edit_Course?.name} onChange={new_category_name}/>
Here is where I validate form input for my state variable
const formValidation = ():void => {
if(state_category_name && state_category_name.trim()){
state_form_Validation = false;
} else {
state_form_Validation = true;
}
setState_form_validation(state_form_Validation);
};
here is my state variable that holds the value of the input box which then gets sent to server.
let [state_category_name, setState_New_Category_Name] = React.useState<string | undefined>("");
State boolean to enable this button if all input is good
let [state_form_Validation, setState_form_validation] = React.useState<boolean>(true);
<input name="view" disabled={state_form_Validation} type="submit" onClick={() => {submitEdit();history.push("/");}} value="Edit"/>
And my on change event
const new_category_name = (e:any):void => {
setState_New_Category_Name(e.target.value);
formValidation();
};
Any help would be great, thanks!
There's a few things wrong here.
First, don't set state variables explicitly, e.g., myVariable = 'new value'. Only update them with the setter, e.g., setMyVariable('new value'). The setter you get back from the useState hook is what ties you into the component lifecycle and will re-render it based on changes.
onChange should be a function not a value, e.g.,
const handleChange = e => /* set state here */
<input id="editCourse_placeHolder_courseName" type="text"
placeholder={edit_Course?.name} onChange={handleChange}
/>
When you implement the onChange handler, each keystroke will update state. Then, I would validate in the body of the component, e.g.,
const isValid = validateForm()
You don't need to maintain the valid status in state. You care if it's valid each render so you can allow a form submit, so just do it in the body of the component. Set the result of the validation to the disabled prop on your button.
<input name="view" disabled={!isValid} type="submit"
onClick={() => {submitEdit();history.push("/");}} value="Edit"
/>

Form help(HTML/JS)

I'm (very) new to web development and am working on learning back-end currently.
I am trying to figure out how to use multiple inputs inside a form, but am struggling to get the actual input, instead of the element itself using this code to create the form:
<form id="newPostForm">
<input name="titleInput" placeholder="title"><br>
<input name="bodyInput" placeholder="body">
<button>Submit</button>
</form>
and this JS to try and output the user input to the console:
const newPost = document.getElementById("newPostForm")
const title = document.querySelector(".titleInput")
const body = document.querySelector(".bodyInput")
newPost.addEventListener("submit", (e) => {
e.preventDefault()
console.log(title, Body)
})
When I hit the submit button the console displays null null. This is probably a super simple question, but I'd appreciate any help.
After fixing the case issue with your body variable, you need to get the value of the inputs by accessing their value property. Then you want to move those variables into your submit handler, otherwise you're only getting the value once, when the page loads, and they're blank:
const newPost = document.getElementById("newPostForm");
newPost.addEventListener("submit", (e) => {
const title = document.querySelector(".titleInput").value;
const body = document.querySelector(".bodyInput").value;
e.preventDefault()
console.log(title, body)
})
<form id="newPostForm">
<input name="titleInput" class="titleInput" placeholder="title"><br>
<input name="bodyInput" class="bodyInput" placeholder="body">
<button>Submit</button>
</form>

How to clear file(s) selection from file input after the data has successfully be submitted?

I am using react.js, I have a form, that I am submitting to an API and the form works fine up to the point where I want to clear the fields. Well actually one field in particular, the file input. I can't get it to reset back to "No File Selected", I've tried creating a files= attribute and controlling it through the state, and everything. Nothing is working, what am I missing?
I only want to reset it when there has been a successful submission.
What is the right approach to this.
<input
type="file"
name="js-case-upload"
className="form-control-static"
filename={this.state.files}
accept="image/*"
onChange={ this._onChangeFileInput }
/>
Considering the input have id myFile, then the file can be reset by vanilla javascript like the following:
document.getElementById("myFile").value = "";
const Upload = ({ onUpload }) => {
const ref = useRef();
const onChange = (e) => {
onUpload(e.target.files, () => {
ref.current.files = null;
});
};
return <input ref={ref} onChange={onChange} type="file" />;
};
I put a callback once I uploaded the file. On the callback I just set my files to null.
Consider adding a ref="file" to you file input, and after submitting the data, use something like this.refs.file.value = ''.
EDIT:
Even a simpler solution: https://jsfiddle.net/n06qk9h4/

Working form without action

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;
}

Categories