I'm curious what the cookies have to do with the onclick handling, at all.
And if it really is onclick, what is the user clicking on to select a quantity??? If radio buttons, then why even display buttons for quantities not in stock? Or even if it's a <select> for quantity, same question. If it's simply an <input> box for quantity, then don't you mean
onchange will trigger the quantity check?
If it's an <input>, then I'd probably have the PHP/JSP/ASP code create the <form> with a hidden field that matches the <input> and holds the current inventory amount.
Example:
Code:
<input type="hidden" name="prod_7731_inv" value="3" />
<input type="text" name="prod_7731_qty" />
Now you can attach onchange handlers to all the "prod_xxx_qty" <input>s and the code is simple:
Code:
function attachQuantityChecks()
{
var form = document.forms[0];
for ( var e = 0; e < form.elements.length; ++e )
{
var elem = form.elements[e];
if ( elem.name != null && elem.name.match(/^prod_\d+_qty$/) != null )
{
elem.onchange = function(){ checkQuantity(this); }
}
}
}
window.onload = attachQuantityChecks;
function checkQuantity( inp )
{
var invname = inp.name.replace(/_qty/,"_inv");
var inv = Number(inp.form[invname].value);
var qty = parseInt( inp.value );
if ( isNaN(qty) || qty < 0 )
{
alert("Invalid quantity");
return false;
}
if ( qty > inv )
{
alert("Sorry, we only have " + inv + " in stock");
return false;
}
return true;
}
And I know I got carried away. Sorry. Kind of thinking out loud on the easiest way to do this. But note that the above code can be quite nicely put in a separate external JS file, as many JS purists would urge.