Click to See Complete Forum and Search --> : Functions and the DOM


mishkin
06-11-2006, 06:53 PM
OK, here's the problem, hopefully someone will have better luck than me.

I'm trying to get the value of a textbox using DOM within a function (sounds easy eh?). My site is highly dynamic so the document object model is used everywhere, this is the first problem i've run into.
If my text box were to look like this:

<input type="text" id="test">

And my function something like this:
<script>
function go()
{
something = document.getElementById("test").value
}
</script>

If I run the function this way I get an alert box with the value of "test":
<script>
function go()
{
something = document.getElementById("test").value
alert(something)
}
</script>

HOWEVER, the script breaks if I do this:
<script>
function go()
{
something = document.getElementById("test").value
return something
}
somethingelse = go()
alert(somethingelse)
</script>

I've even tried to return a something else like this:
<script>
function go()
{
something = document.getElementById("test").value
anotherSomething = 1
return anotherSomething
}
alert(anotherSomething)
</script>
Even that wouldn't work :(

It seems that each time I use DOM in a function, the function loses its ability to return a value, but retains all other functionality. :/
HELP!!!!!!

phpnovice
06-11-2006, 07:15 PM
Doing this:
<script>
function go()
{
something = document.getElementById("test").value
return something
}
somethingelse = go()
alert(somethingelse)
</script>
will fail unless this is placed *after* the "test" object in the document body.

mishkin
06-11-2006, 07:25 PM
Ok, but what if the function is placed in <head> and is called AFTER the <input> is declared. That's how mine is setup and it doesn't work. Another problem that could be related to this is that my <input> came into existance via document.createElement("<input type='text' id='test'>")
Now I can still read the value of the test object with a function, I just can't return a value from that function. :/

phpnovice
06-11-2006, 07:37 PM
You can place this in the HEAD:
<script>
function go()
{
return document.getElementById("test").value;
}
</script>
and place this in a button on your page and it will work:

onclick="alert(go())"

If it fails, just change the id "test" to a different id in both places.
There may be a conflict with that word.