PDA

View Full Version : Unwanted string-to-object conversion when passing function argument


Tails
04-12-2004, 05:05 PM
The script below creates variable 'n' with the value "str". When I document.write a <select> element with an onchange() attribute, I feed the onchange() event the variable n. I expect it to be passed as a string, but for some reason it's passed as an object and I get an 'str is undefined'. I tried using n.toString() for extra assurance, I tried using escaped quotes into the document.write thinking they would let it be parsed as a string after the write, but nothing works.


<form action="">

<script type="text/javascript">
function test(X)
{
//alert(X)
//alert(typeof(X))
}


n="str"
document.write('<select onchange="test('+n+')"><option value="0">Sonic</option><option value="1">Tails</option></select>')
</script>

</form>


For the record, the real page is at http://xfox.digibase.ca/re/gen/skc
Each row of <select>'s and checkboxes at the top are dynamically written with some nested loops. I'm trying to assign IDs with a naming scheme relating to the loop increments (each would be a unique ID). And each <select> tag would have an onchange() event with the loop counts passed on. The function called should uncheck the appropriate checkbox (the one in the row). It seems the problem is a limitation in which it parses the document.write, then the innerHTML, and then the arguments in the attributes such as onchange(). Using 'this' when passing document.write functions is another nightmare.

nolachrymose
04-12-2004, 07:04 PM
You're not passing the parameter as a string for the onchange event. It's as if you're calling:

onchange="test(str);"

...which is not what you want. You must have quotes surrounding the variable for it to pass as a string.

document.write('<select onchange="test(\''+n+'\')"><option value="0">Sonic</option><option value="1">Tails</option></select>')

Hope that helps!

Happy coding! :)

Tails
04-12-2004, 07:09 PM
The problem with that is that it reports it as "invalid character." But even if that wasn't the case, it would probably think I passed "n" as a string instead of parsing variable n.

EDIT: It works ^_^.
(\''+n+\'') doesn't work (simple string escapes outside instead of inside), but
('\'+n+'\') does work.

Thanks alot :thumbsup: