Search code examples
javascriptparsefloat

parsefloat('string' + var) syntax issue


I have a string that equals 'Res' described by:

ResEmp = drpdwn.id.substring(3,6)

If I wanted the following code:

parseFloat(AppResYrs.value)

to get 'Res' from the ResEmp variable, what syntax would I use?

I've tried parseFloat('App' + ResEmp + 'Yrs.value') and parseFloat(('App' + ResEmp + 'Yrs').value) and they don't work. Thank you!

Edit: The following code: alert(ResEmp); alert(parseFloat(AppResYrs.value)); alert(parseFloat('App' + ResEmp + 'Yrs').value); returns 'Res', '0' and 'undefined'. The first two are correct. I want the last one to return 0 also, because I want it to mean the same thing as the second.


Solution

  • Assuming it's the ID of a DOM element, you'd do;

    parseFloat(document.getElementById("App" + ResEmp + "Yrs").value);
    

    If it's a global object with value attribute, you could cheat and do;

    parseFloat(window["App" + ResEmp + "Yrs"].value));
    

    Otherwise you can't access it.