How to pass value from Asp.Net for JavaScript

How to write x and y in my TextBox, I am writing this but not working

 <script language="javascript" type="text/javaScript">
     function PantallaResolucion()
     {
         var x = screen.width.toString();
         var y = screen.height.toString();
         var xx = document.getElementById("HiddenField1");
         var yy = document.getElementById("HiddenField2");
         xx.value = x;
         yy.value = y;
     }
</script>

my asp.net code

<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:HiddenField ID="HiddenField2" runat="server"  />

C # code

protected void Page_Load(object sender, EventArgs e)
{
    string c = "<script language='javascript'> PantallaResolucion(); </script> ";
    ClientScript.RegisterStartupScript(this.GetType(), "PantallaResolucion();", c);
    TextBox1.Text = HiddenField1.Value.ToString() + "x" + HiddenField2.Value.ToString();// NOT WORK**
}
+4
source share
2 answers

You can try the following:

var xx = document.getElementById("<%= HiddenField1.ClientID%>");
var yy = document.getElementById("<%= HiddenField2.ClientID%>");

You can look here to see a very detailed explanation of why this is necessary. According to this link, in a few words:

When the web server control is displayed as an HTML element, the identifier attribute of the HTML element is set to ClientID property. The ClientID value is often used to access the HTML element in the client script using the document.getElementById method.

A more understandable approach to the whole problem would be as follows:

script , </body>

<script>
    function PantallaResolucion(){
        var width = screen.width.toString();
        var height = screen.height.toString();
        var hiddenFld1 = document.getElementById("<%= HiddenField1.ClientID%>");
        var hiddenFld2 = document.getElementById("<%= HiddenField2.ClientID%>");
        hiddenFld1.value = width;
        hiddenFld2.value = height;
        var textBox1 = document.getElemenetById("<%=TextBox1.ClientID%>");  
        textBox1.value =  hiddenFld1.value + "x" + hiddenFld2.value;
    }
</script>

Page_Load. , . script.

+2

, . :

<script language="javascript" type="text/javaScript">
    var text = document.getElementById("<%= TextBox1.ClientID%>"); 
    var x = screen.width.toString();
    var y = screen.height.toString();
    text.value = x + ' ' + y;
</script>

, ,

+1

Source: https://habr.com/ru/post/1648430/


All Articles