views:

267

answers:

3

I am working in JavaScript coding. I have created a text area with name OQ_0 and value "0". When i use eval() method for that field in JavaScript it is giving the value undefined. The below are the part of JavaScript code

var tempOpenQtyStr = "document.InitiateReturnsForm.OQ" + "_" + 0; 
var tempOpenxQtyStr = eval(tempOpenQtyStr).value;
alert('Manuals =' + document.InitiateReturnsForm.OQ_0.value);
alert('eval(tempOpenxQtyStr ) =' + eval(tempOpenxQtyStr));
alert('eval(tempOpenxQtyStr).value =' + eval(tempOpenxQtyStr).value);

Output:

Manuals = 0
eval(tempOpenxQtyStr ) = 0 --- Here it is suppose to show "[object]"
eval(tempOpenxQtyStr).value = undefined.

Kindly help me out what is change to do. Thanks in advance.

+3  A: 

Why not just use document.InitiateReturnsForm["OQ_" + 0].value?

Ignacio Vazquez-Abrams
+1  A: 

Try

alert('eval(tempOpenxQtyStr ) = ' + eval(tempOpenQtyStr));
alert('eval(tempOpenxQtyStr).value = ' + eval(tempOpenQtyStr).value);

In the second and third alert you are evaluating the second variable which stores the value of the first evaluated object. That's why the error occurs.

rahul
Thanks @Phil for the edit.
rahul
A: 
alert('eval(tempOpenxQtyStr ) =' + eval(tempOpenxQtyStr));

Since you put a string, not an object, inside tempOpenxQtyStr, it evaluates that string and returns 0.

alert('eval(tempOpenxQtyStr).value =' + eval(tempOpenxQtyStr).value);

Here you're using a method on a variable that contains a string. That doesn't work. It doesn't have that method, that's why it returns undefinied.

You might want to try doing eval(tempOpenxQtyStr.value) instead of eval(tempOpenxQtyStr).value since the last one does basically nothing, just evaluating an object and then fetching the objects value (it doesn't eval the value itself).

Oskarols