Tuesday 5 July 2011

Add “increment field” functionality to Magento’s quantity fields

Here is an Example of dynamically created div element and populated it with paragraph tags that contain “+” and “-” signs. It looks like this:


To create Something like this you need Following code

var parentTD;
    var newDiv;
    var navigationDiv;
    var i = 1;
    var currentElement = null;
    $$('input.qty').each(function(el){
        parentTD = el.parentNode;
        newDiv = document.createElement('div');
        Element.extend(newDiv);
        newDiv.id = i++;
        newDiv.update(parentTD.innerHTML).innerHTML; //set new input inside new div
        parentTD.update().innerHTML; //erase old input
        parentTD.appendChild(newDiv); //show new div
        navigationDiv = document.createElement('div');
        Element.extend(navigationDiv);
        navigationDiv.update('<p class="up">+</p><p class="dn">-</p>').innerHTML;
        newDiv.appendChild(navigationDiv);
    });
    $$('p.up').each(function(el){
        el.observe('click',function(event){
            currentElement = el.parentNode.previous();
            i = 0; //In case we get in to infinite loop
            while(currentElement.type != 'text' && i < 5){
                currentElement = currentElement.previous();
                i++;
            }
            currentElement.value = parseInt(currentElement.value) + 1;
        });
    });
    $$('p.dn').each(function(el){
        el.observe('click',function(event){
            currentElement = el.parentNode.previous();
            i = 0; //In case we get in to infinite loop
            while(currentElement.type != 'text' && i < 5){
                currentElement = currentElement.previous();
                i++;
            }
            if(parseInt(currentElement.value) > 0){
                currentElement.value = parseInt(currentElement.value) - 1;
            }
        });
    });
But as always, please make backup before installation, as this is provided for usage at your own risk.
There’s no Such styling for this implemented, but with some use of CSS you should be able to create something like this  
 as generated HTML structure looks like this:
<div id="1">
    <label for="qty">
        Qty:
    </label>
    <input name="qty" id="qty" maxlength="12" value="1" title="Qty" class="input-text qty" type="text">
    <button type="button" title="Add to Cart" class="button btn-cart" onclick="productAddToCartForm.submit(this)">
        <span>
            <span>
                Add to Cart
            </span>
        </span>
    </button>
    <div>
        <p class="up">
            +
        </p>
        <p class="dn">
            -
        </p>
    </div>
</div>

0 comments:

Post a Comment