Link to home
Start Free TrialLog in
Avatar of siouxRules
siouxRules

asked on

convert string to object

in jscript, how would i convert a string that contain object like "document.form1.input1.value" to the actual object itself.



Avatar of knightEknight
knightEknight
Flag of United States of America image

var theInputObj = eval("document.form1.input1");
... then you can do this:

alert( theInputObj.name );
alert( theInputObj.value );

etc
Avatar of siouxRules
siouxRules

ASKER

thanks, but i tried it and it didn't work.  when i pass the string to the eval function it return an object but when i do

theInputObj.value

it's undefine.  


thanks, but i tried it and it didn't work.  when i pass the string to the eval function it return an object but when i do

theInputObj.value

it's undefine.  


Can you show me the code you are using, including the HTML for the FORM and in INPUT?  Thanks
function calculate()
{
      var i, childString,total
      var childObject
      total = 0
      for(i= 1 ; i<=10; i++)
      {
      childString = "document.form1.child" + ("" + i) + "quan"
      childObject = eval(childString);
      total = total + childObject.value
      }
      document.form1.totalQuan.value = total;
}

this function call by submition of the form1 which has child1Quan, ..., child10quan in the form.  the form is really big, i don't think i should post it.

thank you.
 
"child1Quan" will be different than "child1quan" -- js is case sensitive.

Also, you should do this to calculate the total:

total += parseInt(childObject.value,10);

instead of  total = total + childObj.value   because childObj.value is a string, not a number.
... p.s.  use parseFloat if the value may contain decimals.
ASKER CERTIFIED SOLUTION
Avatar of knightEknight
knightEknight
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
.. this assumes a form like this:

<FORM name='form1'>
<INPUT name='child1Quan' type='text'>
<INPUT name='child2Quan' type='text'>
<INPUT name='child3Quan' type='text'>
....
<INPUT name='child10Quan' type='text'>
</form>
thank you

su