Incrementing and decrementing a textbox value by one using onClick

I'm looking for help with a JavaScript solution without using jQuery or any plugins, specifically for Cordova/PhoneGap. I am new to JavaScript and learning as I go, so please bear with me.

My goal is to create a functionality where there is a textbox with buttons on each side - one for adding 1 to the textbox value (+) and the other for subtracting 1 (-). When the page/app loads for the first time, I want the textbox to show a value of 0. Upon clicking the + button, the textbox should increment by 1 and continue to increase with each click. Additionally, the app should remember the last input value even after it is closed and reopened.

I have encountered some issues during testing, such as causing disruptions in PhoneGap's iPhone gestures, slow increments/decrements, and the possibility of negative values despite setting a minimum of 0. The code snippet includes localStorage which might not work due to sandboxing, so I may need to use JSFiddle instead.

window.onload = function(){
var CapsNum = localStorage.getItem("CapsNum");

if(CapsNum == null) {
CapsNum = "0";
} else {
document.getElementById("caps").value = CapsNum;
}}
window.onbeforeunload = function(){
localStorage.setItem("CapsNum", document.getElementById("caps").value);
}
function PlusCaps(){
localStorage.setItem("CapsNum",document.getElementById("caps").value++);
}

function MinusCaps(){
localStorage.setItem("CapsNum",document.getElementById("caps").value--);
}
<input type="button" id="plus" class="button" value="+" style="margin-left:10px" onclick="MinusCaps()" />
<input type="tel" id="caps" maxlength="3" size="3" min="0" max="999" pattern="[0-9]" value="0" />
<input type="button" id="minus" class="button" value="-" style="margin-right:10px" onclick="PlusCaps()" />

Answer №1

It appears that you are updating and storing the value in local storage, which does not automatically update the value on the page. I have created a small function based on your example that both updates the state in local storage and reflects the changes in the textbox simultaneously.

window.onload = function() {
  //var CapsNum = localStorage.getItem("CapsNum");

  if (CapsNum == null) {
    CapsNum = "0";
  } else {
    document.getElementById("caps").value = CapsNum;
  }
}
window.onbeforeunload = function() {
  localStorage.setItem("CapsNum", document.getElementById("caps").value);
}

function PlusCaps() {
var nextValue = parseInt(document.getElementById("caps").value) + 1;
  setNextValue(nextValue);
}

function MinusCaps() {
var nextValue = parseInt(document.getElementById("caps").value) - 1;
  setNextValue(nextValue);
}

function setNextValue(nextValue) {
  //localStorage.setItem("CapsNum", nextValue);
  document.getElementById("caps").value = nextValue;
}
<input type="button" id="plus" class="button" value="+" style="margin-left:10px" onclick="PlusCaps()" />
<input type="tel" id="caps" maxlength="3" size="3" min="0" max="999" pattern="[0-9]" value="0" />
<input type="button" id="minus" class="button" value="-" style="margin-right:10px" onclick="MinusCaps()" />

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

What is the best way to access a value within a JSON object in a React render method?

Overview I am currently working on creating a blog using React and JSON data. Upon checking this.state.blogs, I am getting the output of: [object Object],[object Object],[object Object]. I have attempted to use the .map function but I am not sure how to ...

JavaScrip $("").text(); is a straightforward way to recognize and extract

At the moment, I am utilizing the jQuery script below: $("TD.info > font").text(); when this specific HTML structure is present on a webpage: <td class="info"> <font> 3001474535 </font> </td> I had the idea to tweak t ...

Encountering AngularJS promise data parsing issues

I am trying to work with promises in AngularJS. However, I encountered an error while parsing the backend response in AngularJS. What could be the issue here? This is the HTML code: <div ng-app="clinang" ng-controller="pacientesCtrl"> <a ...

The output of JSON.stringify() when given a single value as input

The JSON.stringify() function is designed to convert a JavaScript value into JSON format. console.log(JSON.stringify('a')); //output: "a" console.log(JSON.stringify(1)); //output: 1 console.log(JSON.stringify(true)); //output: true However, tec ...

What are some strategies for optimizing speed and efficiency when utilizing jQuery hover?

While developing a web application, I have created a grid using multiple div elements that are X by Y in size, determined by user input. My goal is to change the background color of surrounding divs within a certain distance when hovering over one particul ...

What are the steps for applying a Bootstrap class to an element?

I keep encountering this error in the console: Uncaught DOMException: Failed to execute 'add' on 'DOMTokenList': The token provided ('si col-md-4') contains HTML space characters, which are not valid in tokens. Below is a ...

Tips on extracting a value from a subscription

I am trying to figure out how to pass a value from a subscribe function to a variable so that I can manipulate it later on. For example: getNumber: number; I need to be able to access and use the variable getNumber in the same .ts file. someMethodT ...

Transferring a CSV file to the server from a React application using multi-part form

In order to post a CSV file to an API using React, I have attempted to do so in multipart form. While many tutorials and websites suggest using the fetch() method for sending files to a server, I am encountering some challenges. The issue lies with my RES ...

Guide on displaying a real-time "Last Refreshed" message on a webpage that automatically updates to show the time passed since the last API request

Hey all, I recently started my journey into web development and I'm working on a feature to display "Last Refreshed ago" on the webpage. I came across this website which inspired me. What I aim to achieve is to show text like "Last Refreshed 1 sec ago ...

The functionality of the Hubot script is restricted to Slack conversations where I initiate a direct message with the

At this very moment, my automated Hubot assistant is functioning properly. When I send the following message via direct message to the robot in Slack: qbot !npm bower The response provided by the robot contains a link: https://www.npmjs.com/package/bowe ...

How to insert text into a text input using onKeyPress in react.js

I am looking to simulate a typing effect where the phrase 'Surveillance Capitalism' is inputted letter by letter into a text input field as a user types. However, I encounter an issue when trying to add each individual letter into the input; I re ...

Customizing the display field in an ExtJs Combobox

I am working on a java web application that utilizes an entity class to populate a combobox with ExtJs. The issue I am facing is as follows: Some entries in the displayField may contain html code. To prevent any issues, I used flexjson.HTMLEncoder during ...

Pop-up - maintain the initial value

I'm working on a modal using Bootstrap and React. Inside the modal, there's a dropdown with an initial empty option: <select class="form-control" onChange={this.handleSelectCat}> <option disabled selected></option> < ...

How to Send C# Array as a Parameter to a JQuery Function

I'm currently working on passing a C# array to a JQuery function as a parameter. The C# code I have to call the function is: //Create an Array from filtered DataTable Column var GatepassIDs = defaultView.ToTable().AsEnumerable().Select(r => r ...

When moving the cursor quickly, a vertical line does not appear upon hover

I am facing an issue with the vue-chartJs library. When I move the cursor fast, the vertical line on hover does not show up. However, when I move the cursor slowly, it works perfectly. Can anyone offer assistance in solving this problem? onHover: functi ...

The AJAX call was successful, however, the response did not contain any data

I have a MySQL table where I use a FOR EACH loop to display data on my page. I then make an AJAX request to update the displayed data every time a new row is inserted into the database. Although the AJAX request is successful, it returns empty data. I&apo ...

Issue with JavaScript code for Google Maps API not functioning as expected

Can someone help me troubleshoot why my simple Google Maps setup isn't working? Thanks! HTML <script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBy2rXc1YewdnqhPaaEd7H0I4DTV_pc7fo&"> </script> <div id="map"> & ...

How to mute a particular warning in development mode with Next.js

Currently in the process of transitioning a CRA app to Next.js in order to enhance SEO. During development, I encountered the following warning: Warning: 'NaN' is an invalid value for the 'left' css style property. I am aware of the s ...

Tips on ensuring that the Angular frontend waits for the response from an Express REST call

Upon initializing my user Component, I want to trigger a REST-Call so that the user profile is displayed when the page loads. The process works smoothly as the component communicates with the service, which in turn contacts my express backend to make the n ...

Tips for identifying modifications in an input text field and activating the save button

Currently, I am developing a function that can detect any changes made in the text field and then activate the save button accordingly. This code is being executed in Visual Studio 2017, using HTML and JavaScript. (function () { var customer_addres ...