cant send javascript variable to server-side code behind

40 Views Asked by At

i want to send value (which is in my javascript) to an asp hiddenfield value so i can access the variable in code behind (C#).

so i have a hiddenfield:

<asp:HiddenField id="SendA" value="ee" runat="server" />

and in my javascript:

function test2() {
    
    document.getElementById("<%=SendA.ClientID%>").value = "nice";
    alert(document.getElementById("<%=SendA.ClientID%>").value);
}

but the console says: JavaScript.js:76 Uncaught TypeError: Cannot set properties of null (setting 'value') at test2.

i have the right syntax and it should alert nice , whats my problem?

2

There are 2 best solutions below

0
jepozdemir On

Ensure that your JavaScript code is placed after the HiddenField in the rendered HTML or that it's executed after the DOM has fully loaded. I mean; you may need something like that:

<script>
    // if you have jQuery
    $(document).ready(function() {
        test2();
    });

    // if not
    document.addEventListener("DOMContentLoaded", function() {
        test2();
    });
</script>
0
Albert D. Kallal On

What you posted should work. You don't show how you calling that JavaScript function.

With this markup:

<asp:HiddenField ID="SendA" Value="ee" runat="server" />

<br />

<asp:Button ID="cmdShow" runat="server" Text="set and show value"
    OnClientClick="test2();return false;" />


<script>

    function test2() {

        document.getElementById("<%=SendA.ClientID%>").value = "nice";
        alert(document.getElementById("<%=SendA.ClientID%>").value);
    }

</script>

The result works and is this:

enter image description here

So, this suggests your markup or JavaScript code has some errors, or is incorrectly placed on the page.

Create a blank new test page, and try the above code, or your code - it should work just fine.