How to Clear a Form

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 to clear a form?

As others pointed out, I think you should reconsider the need to blank the form.
But, if you really need that functionality, this is one way to do it:

Plain Javascript:

function resetForm(form) {
// clearing inputs
var inputs = form.getElementsByTagName('input');
for (var i = 0; i<inputs.length; i++) {
switch (inputs[i].type) {
// case 'hidden':
case 'text':
inputs[i].value = '';
break;
case 'radio':
case 'checkbox':
inputs[i].checked = false;
}
}

// clearing selects
var selects = form.getElementsByTagName('select');
for (var i = 0; i<selects.length; i++)
selects[i].selectedIndex = 0;

// clearing textarea
var text= form.getElementsByTagName('textarea');
for (var i = 0; i<text.length; i++)
text[i].innerHTML= '';

return false;
}

Note that I commented out the case in which I clear the hidden inputs. Most of the time, this is not necessary.

For this to work, you need to call the function from the onclick handler of a button (or some other way), e.g. like this:

<input type='reset' value='Reset' name='reset' onclick="return resetForm(this.form);">

You can test it all here on jsFiddle.

If you use jQuery in your project, you can do this with much less code (and no need to change the HTML):

jQuery(function($) { // onDomReady

// reset handler that clears the form
$('form[name="myform"] input:reset').click(function () {
$('form[name="myform"]')
.find(':radio, :checkbox').removeAttr('checked').end()
.find('textarea, :text, select').val('')

return false;
});

});

Also, note that I do not clear the values of hidden inputs, check-boxes and radio buttons.

Play with this here.

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>

Clear form fields with jQuery

$(".reset").click(function() {
$(this).closest('form').find("input[type=text], textarea").val("");
});

How to reset (clear) form through JavaScript?

form.reset() is a DOM element method (not one on the jQuery object), so you need:

$("#client.frm")[0].reset();
//faster version:
$("#client")[0].reset();

Or without jQuery:

document.getElementById("client").reset();

Note: reset() function does not work if form contains any field with attribute:

name='reset'

Clear input fields on form submit

Use the reset function, which is available on the form element.

var form = document.getElementById("myForm");
form.reset();

Formik clear form on button reset

I think resetting to default values is the expected behaviour.

You can get all the fields to empty by passing an argument to resetForm()

<Button
onClick={() => formik.resetForm({
values: {
title: '',
},
type="reset"
text="clear all"
/>

Check the docs here

How to clear an HTML Form, even the form's initial values?

There are 2 ways to make it happen

  • Using PHP session the correct way
  • Using Javascript local storage


Using PHP sessions

Make sure your .php file has session_start() at the top.

Now you need to request the server to save the value(s) you wanna use on "the next visit". This means, requesting the server without refreshing the page through an HTML form submit, using AJAX.

Following JS snippet will post a form to the server, you can modify what to post as easily as eating an apple pie.

fetch(url, {method: 'POST', body: new FormData(form)})

But you have to POST when the user types something so add an eventListener that triggers the fetch method.

document.getElementById('minPrice').addEventListener('keydown', () => {fetch...})

url is the name of the file or the url you wanna POST to,

form is the form you wanna submit, in case you wanna submit some input field(s) alone, replace new FormData(form) by {minPrice: document.getElementById('minPrice').value} and so on.

assign the fetch method to a variable and you can get the server's response using

variable.then(res => res.json()).then(response => //do whatever you want)

On the server side, get the value(s) using the superGlobal $_POST, such as $_POST['minPrice'] and you can save it in the $_SESSION['minPrice'] variable and whenever the user reloads or makes a second visit, the $_SESSION['minPrice '] will assign the last written minPrice to the input field.

Using Javascript local storage

localStorage is built-into javascript and is quite easier to use. Read more about localStorage on MDN docs. Use

localStorage.setItem('minPrice', document.getElementById('minPrice').value)

And assign the localStorage value to the field on every page load.

document.getElementById('minPrice').value = localStorage.getItem('minPrice')

That's it!



Related Topics



Leave a reply



Submit