Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reset the value of a text input when the page reloads?

Firefox (and probably other browsers) want to keep whatever text the user entered in the text input, even after a reload. Just including the default text (that I want the input to revert to) in the html doesn't work:

<input tyep='text' value='default text' />

And neither does trying to use JS

window.onload = function() {document.getElementById("mytextinput").value = 'default text'}
like image 882
zjmiller Avatar asked Mar 31 '11 15:03

zjmiller


People also ask

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

The reset() method resets the values of all elements in a form (same as clicking the Reset button). Tip: Use the submit() method to submit the form.

How do you reset text in HTML?

To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.


2 Answers

You can use plain old HTML :)

Set autocomplete='off' in the attribute

<input type='text' value='default text' autocomplete='off' />

This works on most modern browsers.

like image 110
JohnP Avatar answered Oct 26 '22 09:10

JohnP


Technically, you don't have to run a function onload to clear it--you could just put the javascript right in the page. For instance:

document.getElementById("mytextinput").value = ''

or with jQuery

$("mytextinput").val('');

Note that it's always a good idea to work with a dom listener to ensure that your javascript fires after the dom has been properly built. So, in the example of jQuery, this would be as easy as

$(document).ready(function() {
   $("mytextinput").val('');
});
like image 23
bpeterson76 Avatar answered Oct 26 '22 08:10

bpeterson76