Using a single function for multiple IDs in JavaScript

function increment(value) {
  var txtNumber = document.getElementById(value);
  var newNumber = parseInt(txtNumber.value) + 1;
  txtNumber.value = newNumber;
}

function decrement(value) {
  var txtNumber = document.getElementById(value);
  var newNumber = parseInt(txtNumber.value) - 1;
  txtNumber.value = newNumber;
}
<div class="range">
  <label>Book</label>
  <a href="#" onClick="decrement('book')">subtract</a><input type="text" id="book" value="0" min="0"><a href="#" onClick="increment('book')"> Add</a>
</div>

<div class="range">
  <label>Pen</label>
  <a href="#" onClick="decrement('pen')">subtract</a><input type="text" id="pen" value="0" min="0"><a href="#" onClick="increment('pen')"> Add</a>
</div>

How can I use the same functions for different Id's?

I attempted to use the "this" keyword to select the current Id, but it did not work... and I am striving to accomplish this using JavaScript only instead of jQuery.

Answer №1

To call the functions, you can utilize the id as a parameter. Within the function, take the value and convert it to a number. If it is falsy, such as NaN, set it to zero.

function add(id) {
    var element = document.getElementById(id),
        value = +element.value || 0;

    element.value = value + 1;
}

function sub(id) {
    var element = document.getElementById(id),
        value = +element.value || 0;

        value--;
        if (value < 0) {
            value = 0;
        }
        element.value = value;
}
<div class="range">
  <label>Book</label>
  <a href="#" onClick="sub('book')"><i class="fa fa-minus-circle" aria-hidden="true">-</i></a><input type="text" id="book" value="0" min="0">
  <a href="#" onClick="add('book')"><i class="fa fa-plus-circle" aria-hidden="true">+</i></a>
</div>

<div class="range">
  <label>Pen</label>
  <a href="#" onClick="sub('pen')"><i class="fa fa-minus-circle" aria-hidden="true">-</i></a><input type="text" id="pen" value="0" min="0">
  <a href="#" onClick="add('pen')"> <i class="fa fa-plus-circle" aria-hidden="true">+</i></a>
</div>

Here's a version using an object for storage.

function add(id) {
    storage[id] = storage[id] || 0;
    document.getElementById(id).innerHTML = ++storage[id];
}

function sub(id) {
    storage[id] = storage[id] || 0;
    --storage[id];
    if (storage[id] < 0) {
         storage[id] = 0;
    }
    document.getElementById(id).innerHTML = storage[id];
}

var storage = {};
<label>Book</label> <a href="#" onClick="sub('book')">- </a> <span id="book">0 </span> <a href="#" onClick="add('book')">+ </a><br>
<label>Pen</label> <a href="#" onClick="sub('pen')">- </a> <span id="pen">0 </span> <a href="#" onClick="add('pen')">+</a>

Answer №2

Include the id name when calling the function like this: add('book') or add('pen') and then use it in the JavaScript function.

Additionally, replace book with txtNumber in the java script.

function add(id) {
  var txtNumber = document.getElementById(id);
  var newNumber = parseInt(txtNumber.value) + 1;
  txtNumber.value = newNumber;
}

function sub(id) {
  var txtNumber = document.getElementById(id);
  var newNumber = parseInt(txtNumber.value) - 1;
  txtNumber.value = newNumber;
}
<div class="range">
  <label>Book</label>
  <a href="#" onClick="sub('book')">subtract</a><input type="text" id="book" value="0" min="0"><a href="#" onClick="add('book')"> Add</a>
</div>

<div class="range">
  <label>Pen</label>
  <a href="#" onClick="sub('pen')">subtract</a><input type="text" id="pen" value="0" min="0"><a href="#" onClick="add('pen')"> Add</a>
</div>

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

Accessing nested objects within a JavaScript array for an Express API

My current data sample looks like this: var data = [{ articles : [{ id : '0', url : 'foo', title : 'Foo', body : 'some foo bar', category : 'foo', tags : ...

Refreshing an Angular datatable using promises - reload directive

I am currently using angular-datatables along with promises and everything is working smoothly. I have various actions that can be performed on each record (using angular $http resource) such as changing a status or similar tasks. However, I find that I n ...

Triggering a d3.js event when two radio buttons are both selected

I am currently working with a sample code that displays data based on the selected radio button: http://bl.ocks.org/juan-cb/1984c7f2b446fffeedde To enhance this functionality, I decided to add two sets of radio buttons instead of one by including the fol ...

What steps should I take in Express.js to proceed with a request if Multer does not detect any images?

Within my Express app utilizing Multer, I am hoping to receive form data that could include a file or not, and then proceed with processing it. This form data includes additional information such as a name that should be added to the database regardless of ...

What is the process for inserting a scroll bar within a div element?

   I have recently created a webpage using some divs, along with a bit of CSS and JavaScript. I am struggling to figure out how to add a scrollbar to one of my divs. The code is not overly complex, as it includes both CSS and JavaScript. <html> & ...

Floating motion when dragging

I am looking to create a hover effect while dragging an object over other objects. The catch is that the hoverable objects are inside an iframe, while the draggable object is outside the iframe. You can see what I am trying to achieve in this example ...

Steps for generating an order from a shopping cart in Mongoose and removing the cart from the system

In my current task, I need to: Generate an order based on the items in my shopping cart Include the relevant object attributes in the order response based on the selection in the "select" option Ultimately, I aim to clear or delete the cart once the order ...

The functionality of the State Params is not functioning as expected

Switch to a different page using parameters by $scope.singlepage = function($url) { $url; console.log($url); $state.go('app.paymentinfo', { "userId": $url}); }; Include state and State param her ...

Is it possible to use both parameters and callback functions in the MongoDB update() function in tandem?

I am looking to create a custom callback function that will check the success of the update() process and return a Q promise based on the outcome. var myCustomFunction = function (name, email) { var deferred = Q.defer(); MongoClient.connect(mongodbU ...

CSS linking causing pages to crumble

Out of nowhere, while working on my project today, my page suddenly collapsed. It was a frustrating sight to see. Immediately, I went back to Dreamweaver and used cmd+z to undo a few steps, but there was no visible issue. Despite this, my page continued t ...

Tips on transforming String Format information

My Json data is structured like this: var d = "1,3,2,4" I want to convert it to: var d = [3,5,3,6] I attempted the following: success: function (Response) { debugger; var du = (Response.d); var final_string = '[' + du + &apo ...

Click on a thumbnail to open the gallery

I am currently working on implementing a feature that will allow a gallery to open when a thumbnail is clicked. At the moment, the code I have looks like this: <div class="row"> <div class="col-lg-12"> <h1 class="page-h ...

What is the best way to organize objects by their respective dates?

I am retrieving data from a database and I would like to organize the response by date. I need some assistance in grouping my data by date. Below is an example of the object I have: var DATA = [{ "foodId": "59031fdcd78c55b7ffda17fc", "qty" ...

What is the process for passing external JSON data to a task from a file that was generated in a previous task?

Currently facing an issue with the following setup in my Gruntfile: grunt.initConfig({ shell: { // stub task; do not really generate anything, just copy to test copyJSON: { command: 'mkdir .tmp && cp stub.json .tmp/javascript ...

Prompt dialogue box javascript

Issue: I am facing a problem with the confirmation box that appears when I click on the save button. It saves the data correctly when I click OK, but when I click cancel, it doesn't cancel the changes and still saves them. Can you assist me in resolv ...

Resetting text in an input field using CSS

Here is the fiddle link for reference: http://jsfiddle.net/a765q/1/. I noticed that when I click the reset button, the text color changes to grey. Any ideas on how to fix this? ...

What are the best ways to make this date more visually appealing and easy to understand?

Hey there! So I have a date that looks like this: 2022-06-28T17:09:00.922108+01:00 I'm trying to make it more readable, but unfortunately, when I attempted using moment-js in my javascript/react project, it threw an error stating "invalid format". ...

Switching hamburger menu icons in Vue.js

I am trying to change a hamburger menu icon in my header to a cross icon when it is clicked. I have created a function in the computed property of my Vue template, but I'm not entirely sure about the implementation. How can I achieve this? Below is t ...

Run a PHP function using <button onclick=""> tag

Is it possible to trigger the execution of a PHP script when clicking an HTML button? I am aware that simply calling a PHP function directly from the button's onclick event like this: <button onclick="myPhpFunction("testString")">Button</butt ...

Is it possible to utilize the useEffect hook in React to dynamically refresh the page content?

I've been attempting to utilize the useEffect hook in order to trigger a DOM update whenever a specific state or prop changes. Despite the fact that the console successfully logs my tests at the desired times, the DOM update or render does not occur. ...