Thursday 22 November 2018

How to assign a javascript variable to ASP.NET Control in javascript?


Hi Coders,

This post will give you an idea on how to assign a JavaScript variable to Asp.net control at Client Side (i.e., JavaScript).

Here, Controls I used to show a sample code:

1. Hidden Field - Asp.Net Control
2. JavaScript snippet

Steps : 

First create a new web project and then add a new file.
Further, Follow the below steps ,

Step 1:  Create a new Hidden Field in our page 
Example: <asp:HiddenField ID="HiddenFieldGetValueFromJS" runat="server" />

Step 2: Access this hidden filed in javascript
Example: document.getElementById('<%= HiddenFieldGetValueFromJS.ClientID %>').value;

Step 3: Create a new variable in javascript and assign it to the above created hidden field
Example:   
   var valueForHidden=10;
   //Its time to assign this variable : valueForHidden to HiddenField : HiddenFieldGetValueFromJS
   document.getElementById('<%= HiddenFieldGetValueFromJS.ClientID %>').value=valueForHidden;
   
Step 4: To Test it put this hidden field in alert and see the output.
 alert("Value of this Hidden Field is assigned from JS to ASPX Control : " + document.getElementById('<%= HiddenFieldGetValueFromJS.ClientID %>').value);
And here the sample output for the above code




Happy Coding :)

Yours, 
Nuthan Murarysetty.  





















No comments:

Post a Comment