Resetting a form field in JavaScript when clicked

Apologies in advance for the beginner question! I'm currently developing a Calculator app in JavaScript and struggling to make the "C" (clear) button clear the field completely. EDIT: Just to be clear, I want the Clear button to not only clear the field but also wipe out everything stored in memory so that I can initiate a fresh calculation. Using

<input type="reset" value="C"/>
clears the field but retains 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 is causing issues. What am I doing incorrectly?

Answer №1

To reset a form, you can use the following code snippet: link

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

Alternatively, you can clear the value of a text box with this code:

 document.getElementById('output').value = "";

Answer №2

Is it more efficient to utilize the provided reset type?

<input type="reset" value="C"/>

Remember, this should be placed within the <form>.

Answer №3

To clear input fields in a form, I found this method effective:

document.getElementById('elementId').value = "";

If you need to reset elements on the page that are not within a form, you can use this approach:

document.getElementById('elementId').innerHTML = "";

Answer №4

Do you want to achieve something similar to this example?

If so, you can use the following code:

function clearData(input) {
         document.getElementById("output").value = input; 
      }

Answer №5

Is it possible to clear the output text by setting it to an empty string?

Alternatively,

Could it be better to set the output to 0 when building a calculator?

document.getElementById("output").value = 0;

Answer №6

Here is a demonstration of how to clear the value of an input field

<input id="entry" type="text"></input>
<button id="clear">Clear</button>

var entry = document.getElementById("entry"),
    clear = document.getElementById("clear");

function clearfield() {   
    // Add any additional code here to clear other affected elements
    entry.value = "";
}

clear.addEventListener("click", clearfield, false);

View this code on jsfiddle

Furthermore, here is an example showcasing the usage of form.reset

<form id="myForm">
    <input id="entry" type="text"></input>
</form>
<button id="clear">Clear</button>

var clear = document.getElementById("clear"),
    form = document.getElementById("myForm");

function clearfield() {
    // Add any additional code here to clear other affected elements
    form.reset();
}

clear.addEventListener("click", clearfield, false);

Check out the code on jsfiddle

Remember, it is advised to avoid inline javascript and utilize addEventListener for better practices.

For example, instead of using onclick="doit();"

Why choose addEventListener?

addEventListener adheres to W3C DOM standards and offers several advantages:

- Ability to add multiple handlers for an event, beneficial for various DHTML libraries or extensions - Provides control over the event activation phase (capturing vs. bubbling) - Compatible with any DOM element, not limited to just HTML elements

Answer №7

When the C button is clicked, the output value will be cleared

 document.getElementById('output').value = "";

Answer №8

 $(function(){
    $("#YourFieldId").click(function(){
        this.value='';
    });
});

This method utilizes jQuery to clear fields on click by changing the selector to #YourFieldId and removing the if statement while retaining the functionality of clearing the input value.

Using jQuery in this way provides an efficient and clean solution for clearing input fields on click.

If needed, you can implement conditions to check the input before clearing it, similar to how the code above clears input fields with a '0' value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to execute custom JavaScript code in an R Jupyter notebook?

Within my Jupyter Notebook, I am working with the R programming language and would like to integrate javascript functions into it. I'm aware that there are libraries in javascript that can be called from R, but I haven't been able to find any ex ...

Data is not being refreshed by Ajax

In my forum, users are only allowed to edit and delete their own comments. I have set up an "edit" button that opens a modal when clicked, giving the user access to the data they submitted before. I've written an ajax function to target these fields a ...

Troubleshooting Problem with Web Forms and Bootstrap Form Design

Currently, I am utilizing a simplified version of the Admin LTE Bootstrap Theme in an ASP.NET Web Forms Project. In this project type, only one form tag can be used per page. The form tag must encapsulate both the Top (Nav) and Bottom (Side Bar Left & Mai ...

Unhook, add at the beginning, and set requirements jQuery

There are two clickable div elements that can switch classes when clicked. If the first one contains "1", it will be given a class of "active". If the second one contains "2", it will have the class "active" while removing the class from the first one. &l ...

Leveraging the socket.io and express modules independently of npm

I am currently developing a project for an embedded Linux system using busybox created with buildroot. I'm intrigued by the idea of utilizing node.js modules such as socket.io and express without needing to depend on the installation or execution of n ...

Converting CSS into jQuery

I am exploring ways to create a collapsible section with arrow icons (right and down arrows) in jQuery or JavaScript. Can anyone provide guidance on how to convert my CSS styling into jQuery code? Below is the jQuery approach I have attempted: $(document ...

When the open button is clicked, the Div will toggle between open and closed states

Recently, some of my questions have not been well-received, which makes me feel a bit disheartened. It's important to remember to be kind when providing feedback. I've noticed that some people downvote without offering constructive criticism, whi ...

The .ajax() method is having trouble sending data to a PHP database query

Dealing with a persistent issue here. Grateful for all the assistance so far, but I've hit another roadblock. My .ajax() function just won't run. Strangely, the .click() doesn't work unless I have if(field != text) before my .ajax() call, bu ...

I am experiencing difficulty with loading the local images stored in the /public/images directory of my React app

I am currently working on a component called Portafolio.js where I am utilizing the map function to retrieve each object from a file named "trabajos.js" that contains all the objects with their respective properties. My goal is to display an image for each ...

Live Edit API

Currently, I am developing an application that requires near real-time collaborative editing capabilities for documents, similar to the functionality found in Google Documents. Since I am a beginner in this area, I would greatly appreciate any information ...

Retrieve the attributes of DOM elements following a successful AJAX request

Is there a way to retrieve the video duration using video.duration following my ajax video upload? Despite achieving ajax success, this function continues to return NaN. I have attempted methods such as $.when().then or $.when.done() but with no success. ...

Open a new HTML page with jQuery with a click event trigger on an iframe element

Hello everyone, I have a simple question as I am still learning about Jquery. I am attempting to load another .html page whenever a figure element is clicked on this .html page. However, the script tag is not working as expected. Can someone please assist ...

displaying pictures exclusively from Amazon S3 bucket using JavaScript

Considering my situation, I have a large number of images stored in various folders within an Amazon S3 bucket. My goal is to create a slideshow for unregistered users without relying on databases or risking server performance issues due to high traffic. I ...

Exploring the contrasting outcomes between a request post and an axios post

After using request and wrapping it with a promise, I realized that I could write cleaner code by switching to axios. However, I encountered an internal server error (Request failed with status code 401) and since I don't have access to the backend co ...

The history.push function seems to be leading me astray, not bringing me back

Issue with History.Push in Register Component App function App() { const logoutHandler = () =>{ localStorage.removeItem("authToken"); history.push("/") } const [loading, setLoading]= React.useState(true) useEffect(()=>{ ...

How to employ Math.random with multiple variables in JavaScript

Within a function, I have the following statement: Math.random() > 0.5 ? 'spikes' : 'slime' I am interested in adding one more variable, let's call it 'stone', and having the program randomly choose between those th ...

The error message "Cannot read property '$scope' of undefined" indicates that there is an issue

After receiving HTML content in an Angular app, I inject it into the HTML document but struggle to retrieve it. For example, you can see a minimized code on plunker here and in JavaScript here Below is my controller: class ReadCtrl constructor: (@$sco ...

Incorporate a new visual element with a texture in three.js

I'm struggling to apply a texture to a mesh and keep getting this error message: [.WebGLRenderingContext]GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 1 It's frustrating not understanding ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

How can I efficiently utilize HTML/CSS/JS to float items and create a grid that accommodates expandable items while minimizing wasted space?

After meticulously configuring a basic grid of divs using float, I've encountered an issue. When expanding an item in the right-hand column, the layout shifts awkwardly. My goal is to have boxes A and B seamlessly move up to fill the empty space, whi ...