Attempting to populate getElementByID using JavaScript function from CodeBehind proves unsuccessful

When a button is clicked on a form, I need to fill in hidden elements that will be posted. The script below should set the values for these hidden fields:

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <!-- setting all the hidden fields --->
    <script type="text/javascript" >
        function fnGetPara() {
            document.getElementById('EPS_MERCHANT').value     = bta_merchant;
            document.getElementById('EPS_TXNTYPE').value      = bta_txntype;
            document.getElementById('EPS_REFERENCEDID').value = bta_referenceId;
            document.getElementById('EPS_AMOUNT').value       = bta_amount;
            document.getElementById('EPS_TIMESTAMP').value    = bta_timestamp;
            document.getElementById('EPS_FINGERPRINT').value  = bta_fingerprint;
            document.getElementById('EPS_RESULTURL').value    = bta_jumpback;
        }
    </script>
    <!-- finish setting all the hidden fields --->
<form method="post" action="https://....." id="form1" runat="server">
 <div class="docdisplay">     
    <!-- merchant -->
    <input type="hidden" name="EPS_MERCHANT"  id="EPS_MERCHANT" />
    <!-- transaction -->
    <input type="hidden" name="EPS_TXNTYPE"   id="EPS_TXNTYPE" />
    <!-- reference -->
    <input type="hidden" name="EPS_REFERENCEDID" id="EPS_REFERENCEDID"/>
    <!-- amount to be paid -->
    <input type="hidden" name="EPS_AMOUNT"  id="EPS_AMOUNT" />
    <!-- Timestamp -->
    <input type="hidden" name="EPS_TIMESTAMP" id="EPS_TIMESTAMP"/>
     <!-- fingerprint -->
    <input type="hidden" name="EPS_FINGERPRINT" id="EPS_FINGERPRINT" />
    <!-- where we want to go after the payment -->
    <input type="hidden" name="EPS_RESULTURL" id="EPS_RESULTURL" />
    ....
</div>
<div class="docbuttons">
   <asp:Button ID="lblauth" runat="server" Text="Authorise payment" OnClick="lblauth_Click"  />
</div>

Below is the method that handles the click event of the button and sets the values for the hidden fields:

protected void lblauth_Click(object sender, EventArgs e)
{
    // get bank transaction data
    bankTransAct.setTransactValues(orderId, invoiceNo, orderpaid, out bta_merchant, out bta_pw, out bta_txntype, out bta_amount, out bta_referenceId, out bta_timestamp, out bta_fingerprint);

    Page.ClientScript.RegisterStartupScript(this.GetType(), "CallfnGetPara", "fnGetPara()", true);
}

The "bankTransAct" method retrieves values for these hidden fields.

I have tried different variations for the id values but the hidden fields are still not getting filled when I trace the page. However, manual filling of the hidden fields works fine.

Any feedback or suggestions would be appreciated as I'm unable to identify where the mistake lies?

Answer №1

It seems like you are attempting to perform one of the following tasks:

  • Access ASP.NET variables, such as bta_merchant, from JavaScript.
  • Have ASP.NET codebehind retrieve the value of an HTML input that has not been designated as runat="server".

This approach will not function as expected because the client's JavaScript engine is separate from your ASP.NET server back-end.

If I understand your situation correctly, what you may want to do is convert all hidden input elements into server-side controls that can be accessed from your C# codebehind. To achieve this, declare them as follows:

<input type="hidden" name="whatever" id="whatever" runat="server" />

You can then set their values from the codebehind rather than using JavaScript. This way, you will be able to read their values upon post-back or have them submitted with the form data if needed for a third-party payment gateway or similar purpose.

If it is essential to access the HTML element from JavaScript, ASP.NET will provide an ID attribute that differs from the C# property name. In this scenario, utilize the ClientID property:

<script>
var element = document.getElementById('<%= serverSideObject.ClientID %>');
</script>

If the name and ID of the generated client side element are significant, and you don't require that value later (i.e., no post-back occurs), you can opt for the following method:

  • Convert the hidden input into a standard HTML form element, not a server-side control.
  • Use an embedded display expression (<%= … %>) (refer to introduction to inline expressions here) to include the correct value.

In this case, your implementation would resemble the following:

<input type="hidden" name="whatever" id="whatever" value="<%= someCSharpExpression %>" />

Note that the element is not considered a server-side element; hence, it lacks the runat="server" attribute. Consequently, ASP.NET will not alter the element's name or ID. The sole special operation performed by ASP.NET is evaluating someCSharpExpression, transforming it into a string, and substituting it in place of <%= … %>.

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

Using ng-repeat to iterate over an array of strings in Javascript

I am working with a JavaScript Array that contains strings: for(var i =0; i<db.length; i++) console.log(db[i]); When I run the code, the output is as follows: dbName:rf,dbStatus:true dbName:rt,dbStatus:false Now, I am trying to use ng-repeat to ...

Generate an interactive pie chart with visually appealing animations using jQuery, without any actual data

My task involves creating a pie chart to visually display different categories. However, the challenge is that the chart does not contain any data, ruling out options like Google charts or other data-driven chart makers. As a solution, I have turned the pi ...

What is the process for configuring a server page within create-react-app for sending API requests?

As I dive into learning React using create-react-app, my latest project involves making an API request to an external source. Initially, I included this request in the front end of the app as I was working on building it out. However, now I realize the imp ...

Troubleshooting a deep population issue with Self-referential relationships in Mongoose

I am facing an issue with populating a self-referential model recursively multiple times. This is my schema setup: var TestSchema = new Schema({ title: { type: String }, counter: { type: Number }, children: [ { type: Schema.Types.ObjectId, ref: &apo ...

Unleashing the power of dynamic column width in Material UI Grid

Is it possible to dynamically change the column width for grid items within the same container in material UI grid? Sometimes I have 2 grid items that need to display in the same row, and other times I have 4 grid items that I want to appear in the same r ...

What could be causing the inability to 'GET' a page on an express app?

As a beginner in web app development, I've been self-teaching Node Express. While I've had success running simple express apps on Cloud9 environments, I'm facing difficulties getting them to work with VS Code. The server starts up fine, but ...

JavaScript identifier used for a widget within the Odoo platform

Suppose you have two widget in a view. After performing an action on the first widget, you need to update the second widget by calling display_field. How can you determine the identifier for the second widget? For instance, in the extended definition of a ...

The Combo Box Select2 display is not showing correctly

In my web application, I'm dynamically adding new rows to a table using JavaScript. Each row contains an element where data is loaded from the ViewBag, and I also want to apply the Select2 class to this element. Here is the current code snippet: < ...

How to Incorporate an Anchor Link into a Div as well as its Pseudo Element using CSS, Javascript, or jQuery

How can I make both the menu item and its icon clickable as a link? When either is clicked, the link should work. Here is a CodePen example: http://codepen.io/emilychews/pen/wJrqaR The red square serves as the container for the icon that will be used. ...

Can you explain the functionality behind the expression "this.method.bind(this)"?

Encountered the code for the first time: var Controller = function($scope){ this._scope = $scope; } Controller.$inject = ['$scope']; Controller.prototype.augmentScope = function() { this._scope.a = { methodA: this.methodA.bind( ...

Issue encountered while trying to connect to MongoDB: MongooseServerSelectionError

I am encountering an issue while attempting to establish a connection from my Node.js application to MongoDB using Mongoose. Every time I try to launch the application, I encounter the following error: "Error connecting to MongoDB: MongooseServerSele ...

Is it possible to create a website with a single session for all users using JavaScript

Greetings everyone, I am excited to be posting for the first time on stackoverflow. After dedicating a week to learning javascript and achieving some things I am proud of, I have hit a roadblock. As a self-learner, I kindly ask for your understanding. Cur ...

When utilizing jQuery in HTML, the Marquee will bounce back upon reaching the end

My issue is that when I use a regular marquee, the text simply goes to the end and does not bounce back to the start as soon as it reaches the end of the div. Instead of using a normal marquee, I am looking to achieve this desired effect by utilizing jQue ...

New React Component Successfully Imported but Fails to Render

I've encountered issues with the code I'm currently working on. Dependencies: React, Redux, Eslinter, PropTypes, BreadCrumb Within a view page, I am importing components from other files. The current structure is as follows: import Component ...

Deactivate a function within Bootstrap JavaScript

Is there a way to temporarily disable a function within Bootstrap after a click event? <a href="#"><span class="glyphicon glyphicon-triangle-right" id="btn04" onclick="myfun();"></span></a> Additionally, I am looking for a soluti ...

Having difficulty modifying the values of my input types on the edit page

After successfully adding user values from the add user page, I encounter an issue when attempting to edit these values such as firstname and lastname on the edit page. Please review the code snippet below for any possible errors. import React from ' ...

Transferring the output of a function to a different state

My current challenge involves sending data from one controller to another within an Ionic application. Despite creating a service for this purpose, I am still unable to share the data successfully. The send() function in MainCtrl is meant to pass the data ...

Combining an array of intricate data models to create

Currently, my setup involves using Entity Framework 7 in conjunction with ASP.NET MVC 5. In my application, I have various forms that resemble the design showcased in this image. By clicking on the "new" button within these forms, a Bootstrap modal like t ...

Webpack and terser reveal the names of the source files in the compressed output

Is there a way to stop source filenames from appearing in webpack output even when using Terser for minification? Illustration After minifying my production React app build, the resulting .js output file still contains original source filenames rather th ...

What is the proper way to wait for an async function to finish in JavaScript before returning its result?

Currently, I find myself grappling with a Google Sign-in Authentication application that comprises a React frontend and an Express backend. The hurdle I currently face lies in the validation of tokens on the backend. The documentation for this process prov ...