Jon Martin
Jon Martin

Reputation: 3392

Javascript error: unable to get value, even though it is not null

I have a bit of javascript code that gets and sets the scroll position based on a hidden input field.

<input type="hidden" id="scroll" runat="server" value="0" />

<script type="text/javascript" >
    function setScroll() {
        document.getElementById('scroll').value = document.getElementById("scrollDiv").scrollTop;
    }

    function scrollToPos {
        document.getElementById("scrollDiv").scrollTop = document.getElementById("scroll").value;
    }

And for some reason it says the value of the hidden input field is always undefined. Does anyone have any explanations?

Upvotes: 1

Views: 2002

Answers (1)

rtpHarry
rtpHarry

Reputation: 13125

because you have got runat="server" in there it is probably changing the ID when its generated.

Try this instead:

<script type="text/javascript" >
    var scrollId = "<%= scroll.ClientID %>";

    function setScroll() {
        document.getElementById(scrollId).value = document.getElementById("scrollDiv").scrollTop;
    }

    function scrollToPos {
        document.getElementById("scrollDiv").scrollTop = document.getElementById(scrollId).value;
    }
</script>

Upvotes: 2

Related Questions