How do I clear the previous text field value after submitting the form with out refreshing the entire page?
try this:
Using jQuery:
You can reset the entire form with:
$("#myform")[0].reset();
Or just the specific field with:
$('#form-id').children('input').val('')
Using JavaScript Without jQuery
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
function submitForm() {
// Get the first form with the name
// Hopefully there is only one, but there are more, select the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit
frm.reset(); // Reset
return false; // Prevent page refresh
}
Clearing my form inputs after submission
Your form is being submitted already as your button is type submit
. Which in most browsers would result in a form submission and loading of the server response rather than executing javascript on the page.
Change the type of the submit button to a button
. Also, as this button is given the id submit
, it will cause a conflict with Javascript's submit function. Change the id of this button. Try something like
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
Another issue in this instance is that the name of the form contains a -
dash. However, Javascript translates -
as a minus.
You will need to either use array based notation or use document.getElementById()
/ document.getElementsByName()
. The getElementById()
function returns the element instance directly as Id is unique (but it requires an Id to be set). The getElementsByName()
returns an array of values that have the same name. In this instance as we have not set an id, we can use the getElementsByName
with index 0.
Try the following
function submitForm() {
// Get the first form with the name
// Usually the form name is not repeated
// but duplicate names are possible in HTML
// Therefore to work around the issue, enforce the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit the form
frm.reset(); // Reset all form data
return false; // Prevent page refresh
}
How clear the form inputs after submission?
As your code snippet only contains input
, You can find all inputs using querySelectorAll
and reset its value
.
Example below. When you click the button it resets all the input.
function resetAllInput() {
const allInput = document.querySelectorAll('input');
allInput.forEach( input => {
input.value = "";
})
}
function uploadFiles() {
console.log('uploading files');
resetAllInput();
console.log('Resetted all inputs');
}
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName" placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection" placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
Clear and reset form input fields
The answer here depends on whether or not your inputs are controlled or uncontrolled. If you are unsure or need more info on this, check out what the official docs say about controlled components and uncontrolled components. Thanks @Dan-Esparza for providing the links.
Also, please note that using string literals in ref
is deprecated. Use the standard callback method instead.
Clearing a form with uncontrolled fields
You can clear the entire form rather than each form field individually.
cancelCourse = () => {
document.getElementById("create-course-form").reset();
}
render() {
return (
<form id="create-course-form">
<input />
<input />
...
<input />
</form>
);
}
If your form didn't have an id
attribute you could use a ref
as well:
cancelCourse = () => {
this.myFormRef.reset();
}
render() {
return (
<form ref={(el) => this.myFormRef = el;}>
<input />
<input />
...
<input />
</form>
);
}
Clearing a form with controlled fields
If you are using controlled form fields, you may have to explicitly reset each component inside your form, depending on how your values are stored in the state.
If they are declared individually, you need to reset each one explicitly:
cancelCourse = () => {
this.setState({
inputVal_1: "",
inputVal_2: "",
...
inputVal_n: "",
});
}
render() {
return (
<input value={this.state.inputVal_1} onChange={this.handleInput1Change}>
<input value={this.state.inputVal_2} onChange={this.handleInput2Change}>
...
<input value={this.state.inputVal_n} onChange={this.handleInputnChange}>
);
}
Demo below:
class MyApp extends React.Component {
constructor() {
super();
this.state = {
inputVal_1: "",
inputVal_2: "",
inputVal_3: "",
inputVal_4: "",
inputVal_5: "",
inputVal_6: "",
inputVal_7: "",
inputVal_8: "",
inputVal_9: "",
inputVal_10: ""
};
}
handleInput1Change = (e) => {
this.setState({inputVal_1: e.target.value});
}
handleInput2Change = (e) => {
this.setState({inputVal_2: e.target.value});
}
handleInput3Change = (e) => {
this.setState({inputVal_3: e.target.value});
}
handleInput4Change = (e) => {
this.setState({inputVal_4: e.target.value});
}
handleInput5Change = (e) => {
this.setState({inputVal_5: e.target.value});
}
handleInput6Change = (e) => {
this.setState({inputVal_6: e.target.value});
}
handleInput7Change = (e) => {
this.setState({inputVal_7: e.target.value});
}
handleInput8Change = (e) => {
this.setState({inputVal_8: e.target.value});
}
handleInput9Change = (e) => {
this.setState({inputVal_9: e.target.value});
}
handleInput10Change = (e) => {
this.setState({inputVal_10: e.target.value});
}
cancelCourse = () => {
this.setState({
inputVal_1: "",
inputVal_2: "",
inputVal_3: "",
inputVal_4: "",
inputVal_5: "",
inputVal_6: "",
inputVal_7: "",
inputVal_8: "",
inputVal_9: "",
inputVal_10: ""
});
}
render() {
return (
<form>
<input value={this.state.inputVal_1} onChange={this.handleInput1Change} />
<input value={this.state.inputVal_2} onChange={this.handleInput2Change} />
<input value={this.state.inputVal_3} onChange={this.handleInput3Change} />
<input value={this.state.inputVal_4} onChange={this.handleInput4Change} />
<input value={this.state.inputVal_5} onChange={this.handleInput5Change} />
<input value={this.state.inputVal_6} onChange={this.handleInput6Change} />
<input value={this.state.inputVal_7} onChange={this.handleInput7Change} />
<input value={this.state.inputVal_8} onChange={this.handleInput8Change} />
<input value={this.state.inputVal_9} onChange={this.handleInput9Change} />
<input value={this.state.inputVal_10} onChange={this.handleInput10Change} />
<input type="submit" name="saveCourse" value="Create" />
<input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
</form>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
React - clearing an input value after form submit
You are having a controlled component where input
value is determined by this.state.city
. So once you submit you have to clear your state which will clear your input automatically.
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({
city: ''
});
}
Clear input field in svelte after form submission
Forms have a native reset mechanism which can be triggered via the reset()
function or a button with type="reset"
.
One limitation is that a value set via regular Svelte properties will not be considered the default. To work around this, you can use setAttribute
to set the default value. E.g.
<script>
const value = (node, param) => node.setAttribute('value', param);
const addVendorTest = async (event) => {
const formData = new FormData(event.target)
// [Use formData]
console.log([...formData]);
event.target.reset();
}
</script>
<form on:submit|preventDefault={addVendorTest}>
<input class="form-control" type="text" name="name"
use:value={'Test Name'} required />
<input class="form-control" type="text" name="phone"
required />
<input class="form-control" type="text" name="email"
required />
<button>Submit</button>
</form>
REPL
HTML form not clearing after submitting
the issue is with your calling URL, make sure to check your requested resource, if you are looking for that, there is no success while requesting resource, so that's why your form is not resetting.
check this
const scriptURL = 'https://jsonplaceholder.typicode.com/todos/1'; const form = document.forms['myForm'];
form.addEventListener('submit', e => { e.preventDefault(); fetch(scriptURL, { method: 'POST', body: new FormData(form) }).then(response => { //console.log('Success!', response); form.reset(); alert('cleared'); }).catch(error => console.error('Error!', error.message))})
<!DOCTYPE html><html><body>
<p>Enter some text in the fields below, then press the "Reset form" button to reset the form.</p>
<form id="myForm"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br><br> <input type="submit" value="Reset form"></form>
</body></html>
Related Topics
What Is "Context" in Jquery Selector
How to Delete Document from Firestore Using Where Clause
Angular2:Render a Component Without Its Wrapping Tag
Save File JavaScript with File Name
Keys in JavaScript Objects Can Only Be Strings
Style.Display='None' Doesn't Work on Option Tags in Chrome, But It Does in Firefox
Make Vuejs and Jquery Play Nice
Why Is It Object.Defineproperty() Rather Than This.Defineproperty() (For Objects)
What Does Three Dots Do in Reactjs
Angular2/Spring Boot Allow Cross Origin on Put
Convert Character to Ascii Code in JavaScript
Store Jquery Selector in Variable
Html5 <Audio> Playback with Fade in and Fade Out
Make Checkbox Behave Like Radio Buttons with JavaScript
Class Methods as Event Handlers in JavaScript