1

I'm making a calculator and I can't get my clear button to work in order to clear the form field.

The rest of the calculator works just fine, just the clear button is having issues. I've even tried setting the value itself to a number or string and that has no effect either.

Here's the code:

function clear() {
  document.form.textview.value = '';
}
<form class="form" name="form">
  <input class="textview" name="textview" placeholder="0">
</form>
<input class="button CE-button" type="button" value="CE" onclick="clear()">
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Accurac
  • 29
  • 1
  • Have you tried using `document.getElementById`, or is that not appliable – Examath May 11 '19 at 03:04
  • Possible duplicate of [Javascript Clear fields Function Not Working?](https://stackoverflow.com/questions/30108310/javascript-clear-fields-function-not-working) – Herohtar May 11 '19 at 03:14
  • it does not work because document.form does not exist, you can use document.forms (it's an array) but I highly recommend that use @Herohtar 's approach – ChaosPattern May 11 '19 at 03:18

4 Answers4

2

clear() can't be used as a function name as Jack Bashford pointed out in his answer. However, if you're using a form you should just use the form.reset() function instead of setting the value manually:

<form class="form" name="form">
  <input class="textview" name="textview" placeholder="0">
</form>
<input class="button CE-button" type="button" value="CE" onclick="document.querySelector('form').reset()">

Better yet, just use a reset button:

<form class="form" name="form">
  <input class="textview" name="textview" placeholder="0"><br>
  <button class="button CE-button" type="reset">CE</button>
</form>
Herohtar
  • 5,347
  • 4
  • 31
  • 41
1

Clear is a reserved function in JavaScript - use something else like clearForm:

function clearForm() {
  document.form.textview.value = '';
}
<form class="form" name="form">
  <input class="textview" name="textview" placeholder="0">
</form>
<input class="button CE-button" type="button" value="CE" onclick="clearForm()">
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

Jack Bashford is right. You could also just use a simply jQuery function:

var clearField = function() {
    $('.textview').val("");
}
Ryan Wans
  • 28
  • 5
0

Clear() function can't be used and you can replace with other function name. However using "reset" can be a good option.