Attempting to create a button using JavaScript, however, encountering difficulties with functionality

I'm a beginner in JavaScript and I decided to use an app to help me learn the language. In my index.html file, I have included the following code:

<div data-role="collapsible">
  <h3>Reset Score</h3>
  <button type="button" id="resetscore">Reset</button>
  <script type="text/javascript">
  function reset() {
    localStorage.setItem('total_win', 0);
    localStorage.setItem('total_lose', 0);
  }
  </script>
</div>

And as part of the footer, I added:

`<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>`

Despite my efforts, I am unable to reset the score back to zero. Even adding alert() statements inside the reset() function did not solve the issue.

If anyone has any insights on why this could be happening, I would greatly appreciate your help! Thank you!

Answer №1

Implementing onclick functionality:

<div data-role="collapsible">
      <h3>Reset High Score</h3>
      <button type="button" id="resetscore" onclick="reset()">Reset</button>
      <script type="text/javascript">
      function reset() {
        localStorage.setItem('total_wins', 0);
        localStorage.setItem('total_losses', 0);
      }
      </script>
    </div>

The function is defined but not invoked anywhere. To trigger the function, it should be called within the onclick event of the button.

Answer №2

It is recommended to include an event listener for the click event in your code.

Your ability to modify the DOM can be enhanced by altering the inner HTML, as demonstrated below:

document.getElementById('resetscore').addEventListener('click',function() {
            //localStorage.setItem('total_win', 0);
            //localStorage.setItem('total_lose', 0);
            document.getElementById('total_win').innerHTML = 0;
            document.getElementById('total_lose').innerHTML = 0;
          });
     document.getElementById('win').addEventListener('click',function(){
            var a = parseFloat(document.getElementById('total_win').innerHTML);
            document.getElementById('total_win').innerHTML = (a+1).toFixed(0);
});
   document.getElementById('loss').addEventListener('click',function(){
           var b = parseFloat(document.getElementById('total_lose').innerHTML);
            document.getElementById('total_lose').innerHTML = (b+1).toFixed(0);       
});
<div data-role="collapsible">
      <h3>Reset Score</h3>
      <button type="button" id="resetscore">Reset</button>
      <button type="button" id="win">+1 Win</button>
      <button type="button" id="loss">+1 Loss</button>
    </div>
    <div id="scores" class="ui-grid-b">
    <div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
    <div class="ui-block-b">Total win:<span id="total_win">0</span></div>
    <div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
    </div>

Keep in mind that script tags should not be enclosed within a div element. To ensure proper functionality, place all JavaScript code at the end of the body section, just before the closing tag, following the completion of all HTML content.

Answer №3

Include the following snippet:

<button type="button" onclick="reset()" id="resetscore">

Specify which function to utilize, pay attention to the onclick attribute, triggering the reset function on click

Answer №4

Make sure that your button triggers the reset function

<button id="resetButton" onclick="resetScore()">Reset Score</button>

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

Tips for displaying real-time error notifications from server-side validation using AJAX

Seeking a way to display inline error messages from my Symfony2 Backend without refreshing the page. I considered replacing the current form in the HTML with the validated form containing the error messages returned by the backend through AJAX. However, ...

Struggling to fetch the last and first name from a document in Firestore using VueJs

https://i.sstatic.net/IdZGi.pngWhen trying to retrieve the last name and first name from a document stored upon signup with a field displayName, I encountered an issue. Despite having a common key as displayName, which should allow me to fetch this informa ...

Mysterious sayings encircling the words fetched through ajax

If the localhost is pointing to the folder named www, where the structure looks like: www/ file/test.cpp index.html I want to dynamically load the content of test.cpp into index.html and display it with the help of highlight.js. Below is the cod ...

Determine the originating component in React by identifying the caller

Can you explain how to access the calling component in a React application? function MyCallingComponent() { return <MyReadingComponent/> } function MyReadingComponent() { console.log(callingComponent.state) } ...

Is it possible to implement JavaScript infinite currying for addition that allows for an unlimited number of function calls and an unlimited number

During a recent interview, I was given the task to create a function based on the code snippet below: add(2,3,4)(5,6)(7,8); // Should yield 35 The code snippet above showcases a function called 'add' that can be invoked multiple times and can h ...

Typing into the styled M-UI TextFields feels like a never-ending task when I use onChange to gather input field data in a React project

Having an issue where entering text into textfields is incredibly slow, taking around 2 seconds for each character to appear in the console. I attempted using React.memo and useCallback without success :/ Below is my code snippet: const [userData, setUserD ...

How can the outer function be connected to the resolve method of $routeProvider?

Here is a functional code snippet: $routeProvider.when('/clients', { templateUrl:'/views/clients.html', controller:'clientsController', resolve: { rights: function ( ...

Tips for initializing and updating a string array using the useState hook in TypeScript:1. Begin by importing the useState hook from the

Currently, I am working on a React project that involves implementing a multi-select function for avatars. The goal is to allow users to select and deselect multiple avatars simultaneously. Here is what I have so far: export interface IStoreRecommendation ...

Leverage AJAX for real-time Django Model updates

Seeking insights on how to effortlessly update a Django model through AJAX without reloading the page or requiring user input for saving. Various tutorials address fetching data from Django models using AJAX, yet resources on updating models remain scarce. ...

Ways to Refresh JSONObject Data

Is there a way to automatically reload the JSON data every 30 seconds, so that any changes are reflected in near real-time? The code snippet below dynamically generates JSON data from the database and adds it to a specific div. <script> JSONObject ...

Exploration of how modals are constantly refreshing with each modal switch

Whenever a new modal pops up asking users questions on a car estimate site, the entire component and its child components re-render. Although this behavior is acceptable, the main issue arises when submitting the problems modal, causing the complete comp ...

Displaying a date and time beautifully in jQuery/JavaScript by providing the day of the week along with the specific time

Does anyone know of a Javascript library, preferably a jQuery plugin, that can take datetimes in any standard format (such as ISO 8601) and convert them into user-friendly strings like: Wednesday, 5:00pm Tomorrow, 9:00am Saturday, 11:00pm I'm not c ...

What is the best way to transform a JavaScript array into a neatly formatted JSON string?

Imagine having an object structured as follows: var test = { jsonString: { groups: ['1','2','3','4','5'] } } How could you transform it into a JSON string like this? var test = { jso ...

Is there a way to transfer a component as a prop to another component in React?

Just began my journey with React and coming from a Java background, please bear with me if the way I phrase this question is not quite right. I'm interested in "passing" an instance of a component to another component (which will then use that passed ...

What is the best way to conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...

Inheritance best practices for node.js applications

In C#, the concept of inheritance can be easily demonstrated through classes like Animal and Dog. class Animal { string name; public Animal() { } } class Dog : Animal { public Dog() : base() { this.name = "Dog"; } } When working ...

Manually adjust rotation in Three.js by clicking

I am looking to initiate an animated rotation of an object by clicking a button. I have a basic understanding that the render function operates as an infinite loop and that adding 0.1 to cylinder.rotation.x continuously rotates the object. My goal is to ...

Adjust the width to ensure the height is within the bounds of the window screen?

I am currently in the process of developing a responsive website, and my goal is to have the homepage display without any need for scrolling. The layout consists of a 239px tall header, a footer that is 94px tall, and an Owl Carousel that slides through im ...

Upon upgrading to webpack 5.x, I encountered the error message `Error: getaddrinfo ENOTFOUND localhost:8081` when trying to run `npm run serve`. What could be causing

Recently, I was tasked with upgrading a Vue project from webpack 4.x to webpack 5.x. Prior to the upgrade, my vue.config.js file looked like this: devServer: { port: 8081, public: process.env.PUBLIC_ADDRESS, }, The variable PUBLIC_ADDRESS was defined ...

JavaScript code for downloading data through AJAX and then loading a chart is not functioning as expected

<script> var highchartsOptions = { chart: { backgroundColor: 'rgba(255, 255, 255, 0.1)', type: 'column' }, title: { text: '' }, exporting: ...