Having trouble retrieving hidden field value in JavaScript

I am encountering an issue with retrieving hidden field values that were set during page load in the code behind. The problem arises when attempting to access these values in JavaScript, as they are returning as undefined or null. I am unable to retrieve the values that were initially set during page load in the code behind.

//code behind (C#) example
protected async void Page_Load(object sender, EventArgs e)
{

HiddenField_alt_edit.Value = "[{"unitid":"3072","unit_nameeng":"BOTTLE","purchcost":"2.000","salrate":"4.000","avgcost":"2.000","factor":"2"},{"unitid":"3073","unit_nameeng":"PKT","purchcost":"10.000","salrate":"20.000","avgcost":"10.000","factor":"10"}]";

ClientScriptManager script = Page.ClientScript;
                            script.RegisterClientScriptBlock(this.GetType(), "Alert", "<script type=text/javascript>addAlternativeRowWithData();</script>");

}
//aspx page content declaration
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

<asp:HiddenField ID="HiddenField_alt_edit" runat="server"  Value="i am on."/>

</asp:Content>
// JavaScript function example
function addAlternativeRowWithData(mode) 
{

    alert("test");
    var idvalue = $("#HiddenField_alt_edit").val();
    alert(idvalue);
    alert($nonconfli('#ContentPlaceHolder1_HiddenField_alt_edit').val());
    var myHidden = document.getElementById('<%= HiddenField_alt_edit.ClientID %>').value;
    alert(myHidden);
    var json_string = $nonconfli('#ContentPlaceHolder1_HiddenField_alt_edit').val();
    var arr_from_json = JSON.parse(json_string);
    alert("test 2");
    alert(arr_from_json);
}

Answer №1

The identification number created on the user's end may vary because the Hidden field is a server-side component in your code since you have specified runat="server".

There are typically two methods. You can either set the ClientIDMode to static or use the form instance to obtain the client-side identifier.

For example:

<asp:HiddenField ID="HiddenField_alt_edit" ClientIDMode="static" runat="server"  
                 Value="I am on."/>

Then, the following should function correctly:

var idvalue = $("#HiddenField_alt_edit.ClientID").val();

Alternatively, in the client-side script, you can acquire the identifier as shown below:

var idvalue = $("#<%= HiddenField_alt_edit.ClientID %>").val();

Answer №2

Revise:

HiddenField_alt_edit.Value = [{"unitid":"3072","unit_nameeng":"BOTTLE","purchcost":"2.000","salrate":"4.000","avgcost":"2.000","factor":"2"},{"unitid":"3073","unit_nameeng":"PKT","purchcost":"10.000","salrate":"20.000","avgcost":"10.000","factor":"10"}]

Transformed:

HiddenField_alt_edit.Value = "
[{'unitid':'3072','unit_nameeng':'BOTTLE','purchcost':'2.000','salrate':'4.000','avgcost':'2.000','factor':'2'},{'unitid':'3073','unit_nameeng':'PKT','purchcost':'10.000','salrate':'20.000','avgcost':'10.000','factor':'10'}]"

Additionally, include:

<asp:HiddenField ID="HiddenField_alt_edit" runat="server"  Value="i am on."  ClientIDMode="Static" />

In your JavaScript code, insert this:

const value = document.getElementById('HiddenField_alt_edit').value

const jsonString = JSON.stringify(value)
const json = JSON.parse(jsonString)

console.log(json)
<input hidden id="HiddenField_alt_edit" value="[{'unitid':'3072','unit_nameeng':'BOTTLE','purchcost':'2.000','salrate':'4.000','avgcost':'2.000','factor':'2'},{'unitid':'3073','unit_nameeng':'PKT','purchcost':'10.000','salrate':'20.000','avgcost':'10.000','factor':'10'}]">

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

Executing various tasks concurrently with web workers in Node.js

Looking to read multiple JSON files simultaneously and consolidate the data into a single array for processing on a Node.js server. Interested in running these file readings and processing tasks concurrently using web workers. Despite finding informative ...

How can I delete the global styles defined in _app.js for a particular component in Next.js?

While working with NextJs and TailwindCSS, I encountered an issue where all the extra styles in my globals.css file were causing some trouble. Although it is recommended to import it at the top level in the _app, I tried moving it down to the "layout" comp ...

Determine if the server is operational using Microsoft Edge

To verify the status of my server, I have implemented the code below: <head> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script> function checkServerStatus() { var img = document. ...

Executing a method to retrieve a value from an empty function in Node.js

I am currently dealing with the code snippet below: function done(err, file) { //handling of code here return "test"; } function process() { retext() .use(keywords) .process(sentence, done); return val; } The proce ...

Comparing DOM Creation in PHP and JavaScript

My website currently does not have any ajax requests, and here is a simplified version of my code: class all_posts { public function index($id){ $statement = $db->prepare("SELECT * FROM mytable WHERE id = :id"); $statement->exe ...

What are the methods for providing both successful and unsuccessful promises, with or without data?

Seeking guidance on how to return a promise and an object named output before or after the $http call in AngularJS, specifically using Typescript. How can I ensure it works correctly? topicNewSubmit = (): ng.IPromise<any> => { var self = t ...

Combining Parallel Axios GET Requests Using the Promise.allSettled Method Along With Source Objects

My current challenge lies in successfully merging the keys of the source object containing the URL with the results of Axios GET requests, despite resolving parallel execution using the allSettled Promise method. Here is the array of objects I am working ...

Dealing with errors in a sequelize ORM query: Tips and tricks

Currently, I am implementing Sequelize ORM in my Node/Express project using Typescript. Within the database, there is a 'users' table with a unique column for 'email'. As part of my development process, I am creating a signIn API and ...

What could be the reason behind receiving a TypeError upon refreshing the page, where it claims that a state is not found even though that may not be the actual situation?

Within my application, I have a component called Wall. Users are redirected to the Wall component after successfully logging in from the Login component. In the Wall component, I am retrieving and displaying the user's name that they used during regis ...

Disabling GPS with HTML5/phonegap: A step-by-step guide

Looking to create a function that can toggle GPS on and off for both iPhone and Android devices ...

What is the best way to choose the initial p tag from an HTML document encoded as a string?

When retrieving data from a headless CMS, the content is often returned as a string format like this: <div> <p>1st p tag</p> <p>2nd p tag</p> </div> To target and select the first paragraph tag (p), you can extract ...

Compose an email without the need to access the website

Is there a way to send email reminders to users without having to load the website pages? In the reminder section, users can select a date for their reminder and an email will be automatically sent to them on that date without requiring them to access the ...

SOLVING the issue of page flicker in SVELTE

Within the application below, I am experiencing a peculiar page flicker effect that is often associated with AJAX requests. However, in this scenario, the cause is not AJAX-related but rather a conditional statement that triggers the rendering of different ...

What is the best method to close a polygon infowindow when hovering over a map marker?

I am currently working on integrating Google Maps which includes a set of polygons representing state boundaries and markers representing cities within each polygon. I want to display information when hovering over a polygon/state. My question is: how can ...

Looking for guidance on restructuring a JSON object?

As I prepare to restructure a vast amount of JSON Object data for an upcoming summer class assignment, I am faced with the challenge of converting it into a more suitable format. Unfortunately, the current state of the data does not align with my requireme ...

Display information using HTML elements within a loop in JavaScript

I am facing an issue with iterating over an array of objects in JavaScript. Each object contains multiple parameters, and my goal is to extract the data from each object and display it in a table or a grid format. Here is an example of my code: function ...

jquery module for retrieving and updating messages

I want to develop a custom plugin that can be utilized in a manner similar to the following example. This isn't exactly how I plan to use it, but it serves as the initial test for me to fully grasp its functionality. HTML: <div id="myDiv">< ...

Having trouble with the clear button for text input in Javascript when using Bootstrap and adding custom CSS. Any suggestions on how to fix

My code was working perfectly until I decided to add some CSS to it. You can view the code snippet by clicking on this link (I couldn't include it here due to issues with the code editor): View Gist code snippet here The code is based on Bootstrap. ...

An async/await global variable in Javascript is initially defined, then ultimately becomes undefined

As I work on establishing a mongoDB endpoint with NodeJS and implementing this backend, I encounter an issue within the code. In particular, the function static async injectDB sets a global variable let restaurants that is then accessed by another function ...

Generating JSON Data with the Power of JavaScript and JQuery

Looking to dynamically generate a JSON Object with the specified structure: { "deleteId":[1,2,3], "pointId":[1,2,3], "update":[ { "what":"mission", "id":1, "value":"adsda" }, { ...