Dynamic Increment Buttons In Javascript

In this post, I'm going to walk through a sample implementation of dynamic buttons that are able to increment and decrement an input field in javascript. The increment feature will be dynamic, leveraging data from the view to alter which aspects of the page are changed. 

Let's start with the HTML. In this example, I'll be using variable syntax from Laravel Blade to dynamically fill the data, but you can use whatever you're comfortable with. 

<td>
  <i class="fas fa-minus-circle" onclick="increment(-1, '{{ $id }}')"></i>
  <input disabled id='{{ $id }}' value='{{ $amount }}'>
  <i class="fas fa-plus-circle" onclick="increment(1, '{{ $id }}')"></i>
</td>

This HTML snippet consists of 3 key elements: 

1. An icon to reduce the value of our input by one. Notice that I've used font-awesome for the icons, a simple plug and play solution for high-quality SVG icons. 

2. A disabled input with a value equal to the current amount, as established by the blade variable. 

3. An icon to increase the value of our input by one. 

All three elements also leverage $id, a blade variable which will enable us to build a whole set of increment buttons on the page, each one with a different $id. Using an onclick event handler, we use the $id and the value of either -1 or +1 as arguments to send to our javascript function. 

So let's see how we can dynamically update the input using javascript. 

function increment(incrementor, target){
    var value = parseInt(document.getElementById(target).value);
    value+=incrementor;
    document.getElementById(target).value = value;
}

This implementation leads heavily upon document.getElementById to determine which portion of the page we should update, which is why we pass through an a CSS id of $id in the HTML. 

Once we have the element on the page, we retrieve the value of that element and then make sure it is ready to increment or decrement using parseInt. Because our data might be stored on the page as a string, parseInt enables us to pass a string and return an integer of the same value. 

Next, we update our local variable value by either adding or subtracting one. 

Finally, we re-use our strategy of targeting the value of specific CSS id to update the page content with our local variable content. 

In the end, we've created a basic yet dynamic solution that enables us to increment many different values on the same page using the same function.