Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable substitutions in JavaScript 1

Status
Not open for further replies.

dove85

MIS
Aug 8, 2001
19
US

function amt_check(form,field_name,amount)
{
.
.
some code to calculate newamt
.
.
if (field_name == "cost")
{
form.cost.innerText = newamt;
} else if (field_name == "unit_price")
{
form.unit_price.innerText = newamt;
} else if (field_name == "total_cost")
{
form.total_cost.innerText = newamt;
} else if ......
}


Is there a way to substitute the "field_name" in the assignment statements so that the above if/else statements would look like

form.??field_name??.innerText = newamt;


Your help would be appreciated.

Thanks.
Dove85
 
well, first of all, if would be much more compatible to use:

document.form.fieldname.value

innerText is not supported by older browsers




now, you could use:

document.form.elements[field_name].value
theEclipse
eclipse_web@hotmail.com
**\\||It was recently discovered that research causes cancer in rats||//**
 
yeah, right

or use eval (pretty ugly when u can use elements array :))
eval('document.forms.formname.'+fieldName+'.value=value')

or pass field like an object:

html :
~~~~~~~
..
<input type=&quot;text&quot; name=&quot;txt1&quot; onchange=&quot;validate(this)&quot;>
..
~~~~~~~

js:
~~~~~~~
..
function validate(object){
alert(object.value)
}
..
~~~~~~~ Victor
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top