最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - clear input textbox value on load - Stack Overflow

programmeradmin3浏览0评论

I have the following form which is getting pre populated with values on load. I want to have empty input boxes on load using Javascript. However I do not have access to the <body> tag so <body onload="" will not work here. Is there any other way to clear the form fields on load?

<form method="POST" action="">
  <input name="username" id="user" value="" /><br />
  <input name="pwd" id="pass" value="" />
  <input type="submit" value="Go" />
</form>

I have the following form which is getting pre populated with values on load. I want to have empty input boxes on load using Javascript. However I do not have access to the <body> tag so <body onload="" will not work here. Is there any other way to clear the form fields on load?

<form method="POST" action="">
  <input name="username" id="user" value="" /><br />
  <input name="pwd" id="pass" value="" />
  <input type="submit" value="Go" />
</form>
Share Improve this question asked Oct 16, 2012 at 16:55 user544079user544079 16.6k42 gold badges120 silver badges172 bronze badges 0
Add a comment  | 

5 Answers 5

Reset to default 9

You can use window.onload instead.

function init() {
    // Clear forms here
    document.getElementById("user").value = "";
}
window.onload = init;

You could also use one of the nice wrappers for doing this in JQuery, Dojo, or you favorite Javascript library. In JQuery it would be,

$(document).ready(init) 

Try something like:

window.onload = function(){
 document.getElementById("user").value = "";
}

Here's an example

You can run a timeout that will clear the field values. like this:

var t=setTimeout(function(){CLEARVALUES},3000)

Maybe you can add a script tag just after the form.

<script type="text/javascript">document.getElementById("user").value = "";</script>

You can also use jQuery to subscribe to both an individual element's ready (or load) event or the document.

onload=()=>{
    document.getElementById('user').value='';
}

or

onload=()=>{
    document.getElementById('user').setAttribute('value','');
}
发布评论

评论列表(0)

  1. 暂无评论