
Originally Posted by
JLAudioFan
<script language="javascript">
The language attribute has been deprecated in favour of the type attribute for a long time now:
HTML Code:
<script type="text/javascript">
function doRetail(){
var a=document.form1.WholePrice.value * .4;
a+=document.form1.WholePrice.value;
If this price is entered by a user, the first thing you should consider is validating that input:
Code:
function doRetail() {
var controls = document.forms.form1.elements,
wholesale = controls.WholePrice.value;
if(!/^\d+$/.test(wholesale) && ((wholesale = +wholesale) > 0)) {
alert('The wholesale price must be a valid number.');
return;
}
controls.RetailPrice.value = wholesale * 1.4;
}
You mention integers, so the regular expression above will only permit whole numbers. If you really intend any real, floating-point number, then the expression can be changed to
Code:
/^(0|[1-9]\d*)(\.\d+)?$/
If validation isn't an issue, then you can avoid the entire issue by performing a simple multiplication:
Code:
function doRetail() {
var controls = document.forms.form1.elements;
controls.RetailPrice.value = controls.WholePrice.value * 1.4;
}
Let's say I had multiple form items on this page, named WholePrice1, WholePrice2, etc (generated with PHP).
If you mean that the document will contain controls with names like 'WholePrice1' and 'WholePrice2', then the function can be parameterised but not in the way you suggest.
document.form1.WholePrice[x]
The document won't actually have an array of 'WholePrice' controls. There will be a discrete set of uniquely named controls. You'd have to access them - taking the second example above - like so:
Code:
function doRetail(index) {
var controls = document.forms.form1.elements;
controls['RetailPrice' + index].value = controls['WholePrice' + index].value * 1.4;
}
That is, you construct the property names at run-time.
Hope that helps,
Mike
Bookmarks