Creating a javascript variable in c#

Currently, I am working on incorporating the selected index text from a DropDownList into a JavaScript string. My approach involves storing the text in a hidden field and retrieving it through C# to ensure the JavaScript variable retains its value even after the page reloads.

I would appreciate any suggestions on whether using hidden fields is the correct method for this task, as well as guidance on how to set the hidden field value as a JavaScript variable.

<asp:DropDownList runat="server" ID="dropCallbackReason" SelectedIndexChanged="riskSeverityDropDown_SelectedIndexChanged" onChange="javascript:updateCallBackReason()" ClientIDMode="Static" >
       <asp:ListItem Text="-- Select Reason --" Value="1"></asp:ListItem>
       <asp:ListItem Text="Booking" Value="6"></asp:ListItem>
       <asp:ListItem Text="Discussing" Value="11"></asp:ListItem>
       <asp:ListItem Text="Contract" Value="45"></asp:ListItem>
</asp:DropDownList>
<asp:HiddenField id="ValueHiddenField" value="" runat="server"/>

<script type="text/javascript">
      function updateCallBackReason() {
      var ddlReason = document.getElementById("<%=dropCallbackReason.ClientID%>");
      callBackReasonPreString = ddlReason.options[ddlReason.selectedIndex].text;
      callBackReason = callBackReasonPreString.replace(/ /g, '');
      return callBackReason;
      }
      $(document).ready(function () { updateCallBackReason() });
 </script>

Thank you in advance for your help,

Answer №1

Employing a concealed input is a common practice. However, I am unable to find any snippets in your code that are interacting with it.

Answer №2

Consider storing your values in a Session rather than a hidden field for a cleaner approach.

There are two ways to do this: server side or client side.

Using server side Session is simple, but client side Session is less common and may require external libraries like this one: https://github.com/AlexChittock/JQuery-Session-Plugin

Alternatively, you can also utilize Cookies.

//Set cookie
$.cookie("somevar", "5");

// Get cookie
$.cookie("somevar")

//Delete cookie
$.cookie("somevar", null);

I hope this information is helpful.

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

When using Selenium async script in its own thread, it can interrupt the execution of other

Let's consider this situation: Various scripts need to run in the browser. One of them involves sending messages from one browser to another (WebRTC). I am interested in measuring the delay for each operation, especially when it comes to sending mess ...

Troubleshooting Autocomplete User Interface Problems

I am currently working on a website user interface and I have encountered an issue specifically in IE7. When searching for a company, the display is not showing up correctly, as demonstrated in the image below. This problem only occurs in IE7, it works fi ...

What is causing the issue with using classes in Javascript to clear the form?

<!DOCTYPE html> <html> <head> <title>Onreset</title> </head> <body> <form> Username: <input type="text" class="abc"><br><br> Password: <input type ...

Updating ng-table within an Angular controller

Having encountered an unusual issue with ng-table. Here is a snippet of code from my controller: this.category = "Open"; this.category = ["Open", "Accepted", "Rejected"]; this.dataItems = []; var _this = this; this.$scope.$watch("vm.category", function( ...

Why is my update with upsert: true not working in Express and Mongoose?

var logs = [{ mobilenumber: '1', ref: 3, points: 1000, ctype: 'mycredit', entry: 'sdfsdf', entry: 0 }, { mobilenumber: '1', ref: 6, points: 2000, ctype: 'mycredit', ...

JavaScript error: forEach is not a function

I've encountered an issue while attempting to loop through a JSON object to extract data. Whenever I run my code, I receive this error: Type Error: element.listing.forEach is not a function. It's worth mentioning that I've used this method ...

PHP - contact form is live for just 2 hours daily

Hello, this is my first time here and I could really use some assistance. Please bear with me as English is not my strong suit compared to most people here, but I'll do my best to explain my query. So, I have a PHP script for a contact form on my web ...

Accessing JS code from HTML is not possible in React

Attempting to create a list using React, I have utilized the module found here: https://github.com/pqx/react-ui-tree I am currently testing out the sample application provided in this link: https://github.com/pqx/react-ui-tree/blob/gh-pages/example/app.js ...

Is there a workaround for retrieving a value when using .css('top') in IE and Safari, which defaults to 'auto' if no explicit top value is set?

My [element] is positioned absolutely with a left property set to -9999px in the CSS. The top property has not been set intentionally to keep the element in the DOM but out of the document flow. Upon calling [element].css('top') in jQuery, Firef ...

Parsing complex JSON structures using JSON.net and nested where clauses in LINQ can be a challenging task

My goal is to retrieve the dateTimeStart within the ttSheduleDay. The JSON snippet below represents a node of an employee, and the function takes in three parameters: empUID, date, and a value (start/stop/duration). The specific node I aim to select is wh ...

Assigning websockets to a global variable may cause them to malfunction

I'm utilizing websockets in conjunction with JavaScript and HTML5. Here is the code snippet I am currently working with: <input type="text" onFocus="so = new Websocket('ws://localhost:1234');" onBlur="so.close();" onKeyUp="keyup();"> ...

Leverage TypeScript with AngularJS to validate interpolation and binding within HTML documents

While TypeScript can detect compile errors for *.ts files, the question arises if these benefits can be extended to AngularJS views/templates. Consider a scenario where the code snippet below is present: <div ng-controller="HomeController as home"> ...

Manipulate elements by adding and removing classes sequentially based on an array

Previously, some had difficulty understanding my question. I have an array of variables representing the ids of 5 divs. My goal is to change the color of each div sequentially for a brief moment before reverting back, mimicking the behavior of traffic ligh ...

Dynamic calendar with flexible pricing options displayed within each cell

I've been wracking my brain over this issue for quite some time now, but still can't seem to find a solution! Is there a React Calendar out there that allows for adding prices within the cells? I simply want to show a basic calendar where each c ...

Unexpected outcome when converting a while loop to a .forEach statement

Exploring a practical demonstration of sorting an array of objects based on multiple properties, the code implementation involves a while loop (refer to students1 in the snippet below). I attempted to streamline this process by using .forEach, but encounte ...

Having difficulties uploading a file with an AutoIT script

I have been searching extensively without success. My problem is that I've written an AutoIT script that works perfectly when executed independently from C# or Java code. Here's the script: WinWaitActive("File Upload") Send("C:\Users\f ...

Effective methods for importing components in VueJS 2.0

As a newcomer to VueJs, I have a question regarding the best practice for importing components in a Vue Template Project. I currently have some components that are used in multiple views. After downloading an admin template, I noticed that the samples alwa ...

"Encountering issues with calling a Node.js function upon clicking the button

I'm facing an issue with the button I created to call a node.js server function route getMentions, as it's not executing properly. Here is the code for my button in index.html: <button action="/getMentions" class="btn" id="btn1">Show Ment ...

Make sure the division remains fixed even when the window is resized

Having a fixed position and bottom set to 0, I want my div to display at the bottom of the window. The issue arises when the window is resized, causing the div to move up and into other elements. For instance, when opening the console box in Chrome, the f ...

"Can you tell me the method for obtaining an array within an Angular

Within the realm of PHP, there exist certain elements within an array: $this->data['messages']['ms'][] = 'Line1'; $this->data['messages']['ms'][] = 'Line2'; along with a method that return ...