jQuery Counter with Next and Previous Buttons

How to increment or decrement a form field using jQuery, specially useful for quantity fields.

by LW

HTML

<span id="quantity">9</span>
<button class='prev' field='quantity'>Prev</button>
<a class="button prev" href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/32471/Change-400.jpg"  field='quantity' download>Download</a>
<span id="quantity2">9</span>
<button class='prev' field='quantity2'>Prev</button>

JavaScript

jQuery(document).ready(function(){
    // This button will decrement the value till 0
    $(".prev").click(function() {
        // Stop acting like a button
        //e.preventDefault();
        // Get the field name
        fieldName = $(this).attr('field');
        // Get its current value
        var currentVal = parseInt($('span[id='+fieldName+']').html());
        // If it isn't undefined or its greater than 0
        if (!isNaN(currentVal) && currentVal > 0) {
            // Decrement one
            $('span[id='+fieldName+']').html(currentVal - 1);
        } else {
            // Otherwise put a 0 there
            $('span[id='+fieldName+']').html(0);
        }
    });
});