willaim
willaim

Reputation: 23

adding a reset button in javascript

I am very green and starting to learn JS, just started my small project for practice. I found my "reset" button is no longer working, would you guys pls hv some comments? Thanks a lot.

<input type="button" value="Reset" onclick="clear()">
function clear(){
document.getElementById("result").value.reset();}

Upvotes: 2

Views: 19439

Answers (3)

ABGR
ABGR

Reputation: 5205

Change

document.getElementById("result").value.reset()

to

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

And also, rename clear to some other function as clear is a reserved word and does something entirely different.

 function myFunc() {
     document.getElementById("reset").reset();
 }
  <form id="reset">
    Name<br><input type="text"  name=""><br>
    foo<br><input type="text" name=""><br>
    <input type="button" onclick="myFunc()" value="Reset">
 </form>

Upvotes: 0

Nripesh Poudel
Nripesh Poudel

Reputation: 1

There are two ways to solve this error that I figured out. First thing if you want to use reset() then, use the following code:

<form id="result">
<input type="text">
  <input type="button" value="Reset" onclick="clear1()"></form>
<script>
function clear1(){
  document.getElementById("result").reset();}</script>

So if you see here, I have used the tag. Three errors I found in your markup were:

  1. clear() method is already reserved in javascript. clear() method in JavaScript is used for the removal of all the elements from a map and make it empty. So, instead use any other function name like clear1() just like I did.
  2. reset() function works for the tag. So instead of giving input tag an id give that id to the tag.
  3. You don't have to use the value in reset() method Use this method when you have a lot of input tags to perform with. Just wrap it with a tag.

Another method is easy when you have only one or two tags.

<input type="text" id="result">
  <input type="button" value="Reset" onclick="clear1()">

<script>
function clear1(){
document.getElementById("result").value= ''}
</script>

Upvotes: 0

djcaesar9114
djcaesar9114

Reputation: 2137

Watch out, clear is already taken, you should rename your function:

function clearResult(){
  document.getElementById("result").value = ''
}
<input id="result" type="text" />
<input type="button" value="Reset" onclick="clearResult()">

See for example https://developer.mozilla.org/fr/docs/Web/API/Document/clear

Upvotes: 3

Related Questions