Passing values from ASP.NET to JavaScript: A step-by-step guide

How can I input x and y values into my TextBox? I tried the following code but it doesn't seem to work.

 <script language="javascript" type="text/javaScript">
     function ScreenResolution()
     {
         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>

Here is my asp.net code:

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

This is the C# code:

protected void Page_Load(object sender, EventArgs e)
{
    string script = "<script language='javascript'> ScreenResolution(); </script> ";
    ClientScript.RegisterStartupScript(this.GetType(), "ScreenResolution();", script);
    TextBox1.Text = HiddenField1.Value.ToString() + "x" + HiddenField2.Value.ToString();// Issue here**
}

Answer №1

If you're looking for a solution, consider the following steps:

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

For more information on why this approach is necessary, check out this resource. In essence, it explains the significance of using ClientID in client-side scripting:

When a Web server control is rendered as an HTML element, the id attribute of the HTML element is set to the value of the ClientID property. The ClientID value is often used to access the HTML element in client script by using the document.getElementById method.

To simplify the process, consider implementing the following solution:

Insert the provided script at the end of your page, just before the closing tag </body>

<script>
    function ScreenResolution(){
        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>

After that, remove the statements from the Page_Load method. It's worth mentioning that having two hidden inputs might not be necessary. You could potentially remove them and adjust the script accordingly.

Answer №2

Great news! You can complete everything on the client side without the need for server-side logic:

<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>

This solution should meet your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop users from typing specific word in textarea

I'm currently working on a website and I want to prevent users from entering certain words like ".com" or ".net". If any of these words are entered, I simply want them to be replaced with a space. I've already implemented JavaScript code that rep ...

Nightwatch.js - Techniques for waiting until an AJAX request is finished

Currently, I am relying on nightwatchJS for browser automation. A common issue I encounter is that much of the content on my webpage gets updated via ajax calls. To ensure accurate testing, I need a way to pause my testing until the ajax call returns resul ...

Tips for implementing conditional rendering with ReactJS

I have created a React component that generates a list of tasks. Currently, the code works fine with this.props.data, and if the data is empty, no tasks are displayed. My goal is to modify the code so that if the array is empty, a simple text message ...

Android Webview onLoad function provides incorrect height information

When I load a file:// URL into the webview, issues with height calculation arise. Instead of using WRAP_CONTENT, I calculate the height in javascript during the onPageFinished event in Android. However, about 2 out of 5 times, the javascript reports an inc ...

Error: Unable to access the 'fromJSON' property of an undefined object

I am attempting to showcase menu data once the ajax call is completed from the specific page: <head> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"> ...

What is the best way to send a string value from HTML to a JavaScript function as a parameter?

When embedding HTML codes in Java, I encountered an issue where I needed to pass a string value from HTML to a JavaScript function. Initially, I tried using the following code: out.print("<script>init("+macId+")</script>"); However, this meth ...

"Enhancing user experience with Ajax and seamless page updates

I'm currently in the process of developing a web application that includes a feature to trigger a backend action that may take up to 5 minutes. This backend process will run independently from the web app's front-end and back-end functionalities. ...

Switch up the Position of a Frame with jQuery

I'm attempting to cycle through an array of URLs in order to designate them as locations for a frame. The current setup I have can be found on this fiddle: var l = ['0', '1', '2', '3', '4', '5&ap ...

AngularJS utilizes JSON objects to store and manipulate data within

My task requires accessing information from an array that is nested inside another array in Json format. Here's a more detailed example: [ { "id": 1, "name": "PowerRanger", "description": "BLUE", "connections": [ {"id": 123,"meg ...

Node.js encountered an SFTP error stating "Error: connect: An existing SFTP connection is already defined."

Working within my node.js application, I have implemented ssh2-sftp-client to upload an image every 5 seconds. The initial upload functions correctly, but upon repeating the process, I encounter an error message: node .\upload.js uploaded screenshot ...

I'm having an issue where whenever I click on a different page, I keep getting redirected back to the first page

Upon conducting research, I discovered that by implementing the refined code below, I was able to resolve my issue (my other html was also corrected using this solution) setTimeout(function() { datatable_FTP.ajax.reload(null, false); }, 30000); Although I ...

Unexpected geometry encountered with TopoJson and ChartGeo/ChartJS integration

I have successfully used TopoJson and ChartJS to create a map of the UK. However, I am now facing difficulty in drawing two squares off the west coast of GB. Here is my custom-written TopoJson data: const topoData = { type: "Topology", a ...

What is the best way to make message properties accessible to the public while also being able to access them within a web

Situation Our company works with various clients, some using native apps such as iPad and Android, while others use web-based platforms like websites and SmartTVs. We have a central web project that houses common assets used by all clients, including ico ...

Issue with inserting ASP.net details view column data into the database

I am attempting to populate a database using Details View. To insert the CategoryID column, which is a foreign key, I am using a dropdownList in order to restrict users from entering arbitrary numbers. The values for the dropdownlist are sourced from the ...

Using AngularJS instead of jQuery to delete items from the DOM or View

Curious about handling DOM elements in AngularJS, I came across a specific scenario in my View / Webpage <div> <p>I am some text or a comment or something</p> <a href="" ng-click="deleteThisDiv()">X</a> </div> & ...

The v-on:click event handler is not functioning as expected in Vue.js

I am currently learning vue.js and facing some challenges. Below is the code snippet from my HTML page: <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net ...

When implementing jQuery for scrolling on a website, touch gestures may become unresponsive on Safari for iOS devices

While developing a custom website with Angular, I encountered an issue specifically with Safari on iOS. The website is a single-page app with multiple menu sections that trigger a scroll animation when selected using jQuery. Everything was working smoothly ...

Is there a way to obtain a JSON file (or something of the like) containing lightning data from the website http://en.blitzortung.org?

Currently, I am in the process of developing an Android app for my school project. The app will provide real-time notifications about strong lightning strikes near your location. I have come across websites like blitzortung.org and lightningmaps.org, amon ...

What is the best way to retrieve this value using javascript?

Currently, I am developing a browser extension for opera that will search for a specific element on the page when clicked. However, as a beginner in HTML and Javascript, I am completely lost and unsure of what steps to take next. The crucial value I need ...

Discovering a specific element within a deeply nested JavaScript object

let data = [{ "ItemAID" : 1, "ItemADesc" : [ { "ItemBid" : 11, "ItemBDesc" : [ { "ItemCid" : 111, "ItemCTitle" : "TitleC111", }, { " ...