zjmiller
zjmiller

Reputation: 2807

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

Upvotes: 8

Views: 32831

Answers (4)

JohnP
JohnP

Reputation: 50029

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.

Upvotes: 20

nandu.com
nandu.com

Reputation: 343

I think you should do a server side coding on page reload. Page reload is generally a postback type idea . The page gets reloaded from server. If you are doing asp.net , in page_load method add your default text. :)

Upvotes: 0

bpeterson76
bpeterson76

Reputation: 12870

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('');
});

Upvotes: 3

Tom Gullen
Tom Gullen

Reputation: 61773

Try this:

<input type='text' id='mytextinput' value='default text' />
<script>
    document.getElementById("mytextinput").value = 'default text';
</script>

This code should run as soon as the textbox has loaded. The onload event can seem inconsistent, I'm not entirely sure how it behaves in multiple browsers on different actions like refreshing.

You can call the script differently, put it in a function, put it somewhere else etc, but it's good to start with a working version.

If this doesn't work on other browsers there isn't much you can do because some browsers will try and be 'helpful' and always autofill for you.

Upvotes: 0

Related Questions