stock update

by stofke

HTML

<div id="navcontainer">
    <ul id="navlist">
        <li><a href="#" class="current">Item one</a></li>
        <li><a href="#">Item two</a></li>
    </ul>
</div>
<div class="box">
    <h2>Stock of item one</h2>
    <select id="Itemone" size="5" width="50px">
        <option></option>
    </select>
</div>
<div class="box">
    <h2>Stock of item two</h2>
    <select id="Itemtwo" size="5" width="50px">
        <option></option>
    </select>
</div>
<br class="clear"/>
<h2>The effect on the items object (unaffected)</h2>
<span id="items"></span>
<h2>The effect on the stock object</h2>
<span id="stock"></span>

CSS

a {
    font: bold 100% "Lucida Grande", Lucida, Verdana, sans-serif;
}
#navlist li
{
    display: inline;
    list-style-type: none;
    padding-right: 5px;
    
}

#navlist li a.current
{
    font-weight: bold;
}
h2
{
    text-decoration: underline;
    color: #555;
    font: bold 120% "Lucida Grande", Lucida, Verdana, sans-serif;
    margin-top:30px;
    margin-bottom:15px;
}
.box {
    float:left;
    margin-left:5px;
}
.clear {
    clear:both;
}

JavaScript

$(function() {
    var stockItems = {
        "Item one": 2,
        "Item two": 5
    }; //stock object
    var cartItems = {
        "Item one": 0,
        "Item two": 0
    }; //cart object
    var originalItems = {
        "Item one": 2,
        "Item two": 5
    }; //items object
    $("#navlist li a").click(function() {
        var dropDown = $(this).text().split(' ').join('');
        $('#'+dropDown+' option').remove(); //reset the stock dropdownlist on click
        var itemName; //name of the item
        var total_stockItems = stockItems[$(this).text()]; //get total stockitems for an item
        if (total_stockItems > 0) { //total amount of stockitems for an item has to be higher than 0 for to be able to add it to the cart
            stockItems[$(this).text()] -= 1; //counter, updates the stock-object -1
        }
       
        for (i = 1; i <= stockItems[$(this).text()]; i++) {
            $("#"+dropDown).append($("<option></option>").val(i).html(i)); //build the stock dropdown
        }
        //some info on the objects
        $("#items").text("var items =" + JSON.stringify(originalItems) + ";"); //output the items object
        $("#stock").text("var stock =" + JSON.stringify(stockItems) + ";"); //output the current stock object
        return false;
    });
});