Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing a form field in Javascript upon click

Sorry for the newb question in advance! I'm making a Calculator app in Javascript and am having a hard time getting the "C" (clear) button to clear the field. EDIT: To clarify, the Clear button should not only clear the field but also everything held in memory so that I can start a fresh calculation. <input type="reset" value="C"/> clears the field but holds the last buttons I've pressed in memory.

    <script>
      input = "";

      function handleClick(data) {

        input += data;
        document.getElementById("output").value = input;
        console.log(input);
      }

      function evaluateExpression(data) {
        input = document.getElementById("output").value = eval(input);
      }

      function clear(data) {
        input = data;
        input = document.getElementById("output").reset(); 
        console.log(input);
      }

    </script>

    <div id="calculator">

      <form>
        <input type="text" id="output" />
      </form>

      <button onclick="handleClick(1)">1</button>
      <button onclick="handleClick(2)">2</button>
      <button onclick="handleClick(3)">3</button>
      <button onclick="handleClick(4)">4</button>
      <button onclick="handleClick(5)">5</button>
      <button onclick="handleClick(6)">6</button>
      <button onclick="handleClick(7)">7</button>
      <button onclick="handleClick(8)">8</button>
      <button onclick="handleClick(9)">9</button>
      <button onclick="clear(0)">C</button>
      <button onclick="handleClick('+')">+</button>
      <button onclick="handleClick('-')">-</button>
      <button onclick="handleClick('/')">/</button>
      <button onclick="handleClick('*')">*</button>
      <button onclick="evaluateExpression()">=</button>
    </div>

The "clear" function just does not want to work. Where am I going wrong?

like image 900
jenno Avatar asked Dec 08 '22 16:12

jenno


1 Answers

Do reset on form . link

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

or Set the value of textbox like this

 document.getElementById('output').value = "";
like image 54
NullPointerException Avatar answered Dec 26 '22 20:12

NullPointerException