-2

i have this js code on my page:

var mail = 'idEmail';
value(mail);
//function returning the value of an input
function value(input){
  return eval('window.document.Search.'+input).value;
}

I have this error:

TypeError: Cannot read property 'idEmail' of undefined

Why when i change return eval('window.document.Search.'+input).value; by return eval('window.document.forms['Search'].'+input).value; it's work?

document.forms["general"]
or
document.forms[0]
or
document.general 

it's the same

Mercer
  • 9,736
  • 30
  • 105
  • 170
  • 2
    because you forgot `.forms` in the first version – Kaddath Aug 03 '17 at 09:29
  • Oh for crying out loud, do away with the `eval` nonsense ... https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable – CBroe Aug 03 '17 at 09:30

2 Answers2

1

Because you forgot the forms part:

return eval('window.document.forms.Search.'+input).value;

Note that eval is evil. You might as well do:

return document.forms.Search[input].value;
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

In your function you are trying to access a property of an undefined object, in fact .Search isn't a property of window.document but of window.document.forms instead, change it like this:

function value(input){
  return window.document.forms.Search[input].value;
} 

Note:

It's better to avoid using eval, you can get rid of it in your function.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78