admin管理员组

文章数量:1418019

I have some Input fields on my page, these fields are already filled when I refresh the page.

How can I clear the pre-filled input fields without using reset button on page refresh?

function add() {
  var num1, num2, c;
  num1 = Number(document.getElementById("a").value);
  num2 = Number(document.getElementById("b").value);
  c = num2 + num1;
  document.getElementById("answer").value = c;
}
<!doctype html>
<html>
<title>
  addition WEBSITE
</title>

<body>
  <div align="center">
    <h1>addition</h1>
    a= <input id="a"> b= <input id="b">
    <button onclick="add()">Add</button> Sum= <input id="answer">
  </div>
</body>

</html>

I have some Input fields on my page, these fields are already filled when I refresh the page.

How can I clear the pre-filled input fields without using reset button on page refresh?

function add() {
  var num1, num2, c;
  num1 = Number(document.getElementById("a").value);
  num2 = Number(document.getElementById("b").value);
  c = num2 + num1;
  document.getElementById("answer").value = c;
}
<!doctype html>
<html>
<title>
  addition WEBSITE
</title>

<body>
  <div align="center">
    <h1>addition</h1>
    a= <input id="a"> b= <input id="b">
    <button onclick="add()">Add</button> Sum= <input id="answer">
  </div>
</body>

</html>

Share Improve this question edited Nov 13, 2020 at 8:46 F. Müller 4,0629 gold badges43 silver badges52 bronze badges asked Sep 9, 2017 at 18:42 Utpal DuttUtpal Dutt 4034 silver badges18 bronze badges 2
  • 3 Show us your code... – Script47 Commented Sep 9, 2017 at 18:42
  • 2 Not like that, edit it in to your post with correct formatting. – Script47 Commented Sep 9, 2017 at 19:01
Add a ment  | 

2 Answers 2

Reset to default 2

You can clear the fields on window.onload .

 <!doctype html>
<html>
<title>
  addition WEBSITE
</title>
    <head>

    </head>
    <script >
    
    window.onload = function(){
    
        document.getElementById("a").innerHTML = "";
        document.getElementById("b").innerHTML = "";
    
    }

    function add()
        {
        var num1,num2,c;

        num1= Number(document.getElementById("a").value);
        num2= Number(document.getElementById("b").value);
        c=num2+num1;
        document.getElementById("answer").value=c;
        }
    </script>
<body>
    <div align="center">
     <h1>
     addition
     </h1>

     a=  <input id="a">
         b=  <input id="b" >
         <button   onclick="add()">Add</button>    
         Sum=  <input id="answer" >    

    </div>    


</body>    
</html>

Your code should be better. Anyway, if you want the fields to be empty when refreshing the page, create an anonymous function called by itself like this:

function () {
 document.getElementById('a').value = ""; 
}

Get the other input elements and do the same inside this function.

Happy coding !!

本文标签: javascriptClear input field on page refreshStack Overflow