I have an issue in getting the hidden field values, which is been set in page load at code behind. Problem is when i try to get that set values in javascript its giving undefined or null. Not able to get the values which was set in page load at code behind.
//cs code is like this
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 declaration goes like this. Also i am using a master page.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:HiddenField ID="HiddenField_alt_edit" runat="server" Value="i am on."/>
</asp:Content>
// javascript file code goes like this
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);
}
The id generated at client side can differ as the Hidden field is server side control in your code as you have set runat="server".
There are two ways normally. Either make the ClientIDMode static or use the instance in form to get client side id.
Like:
<asp:HiddenField ID="HiddenField_alt_edit" ClientIDMode="static" runat="server"
Value="i am on."/>
and then following should work:
var idvalue = $("#HiddenField_alt_edit.ClientID").val();
or in client side code you need to get id like below:
var idvalue = $("#<%= HiddenField_alt_edit.ClientID %>").val();
Change:
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"}]
To this:
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'}]"
Then, add this:
<asp:HiddenField ID="HiddenField_alt_edit" runat="server" Value="i am on." ClientIDMode="Static" />
In you js, you have to put 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'}]">
Related
I'm trying to add an error label to the top of a panel I have. I have a button created in C# on page load that calls a JavaScript function that I want to display an error message on my panel when clicked.
C#:
private void CreateButton(int pID, string changeType)
{
ASPxButton btn = new ASPxButton();
btn.Text = "Execute Request";
btn.ID = "btn" + changeType;
btn.AutoPostBack = false;
btn.ClientSideEvents.Click = GetClientSideEventHandler(string.Format("OnProcessRequest(s, e, '{0}','{1}')", pID.ToString(), changeType));
TableRow oRow = new TableRow();
TableCell oCell = new TableCell();
oCell.CssClass = "table-cell";
oCell.Controls.Add(btn);
oRow.Cells.Add(oCell);
tblButtons.Rows.Add(oRow);
}
JS:
function OnProcessRequest$(pID, pChangeType) {
document.getElementById('errLabel').value = "Test";
}
ASPX:
<asp:Label ID="errLabel" runat="server"/>
When this code runs, it always throws the following error:
Error: Unable to set property 'value' of undefined or null reference.
I have tried also using:
document.getElementById('<%=errLabel.ClientID%>').value = "Test";
but this also throws the error.
How can I change the value of this label when this button is clicked in JS?
Ok, to change a asp.net label in JavaScript, you can do this:
(we assume you set the label client id mode>
So, if we have label on the page, you can do this:
<asp:Label ID="Label1" runat="server" Text="" ClientIDMode="Static"></asp:Label>
JavaScript to change above is this:
var lbl = document.getElementById('<%=Label1.ClientID%>');
lbl.innerText = "Js lable text changed";
Or
lbl.innerHTML = "<h2>this is some big text by js</h2>"
Be VERY careful with case, and VERY careful with extra spaces etc. in the get Element.
Also, do NOT forget to include the Text="" in your label!!!! (you are missing this!!!).
JavaScript is VERY flakey - one small wrong move, and it just rolls over and goes home. (and the debugger in browsers is on par with a trip to the dentist).
You can also use jQuery.
The above thus becomes this:
var lbl = $('#Label1');
lbl1.text("js jquery text change");
Now, lets do the same for a text box.
our asp.net text box:
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static" ></asp:TextBox>
JavaScript:
var txt = document.getElementById('<%=TextBox1.ClientID%>');
txt.value = "This is js text for text box";
And as jQuery:
var txt = $('#TextBox1');
txt.val("js jquery text for the text box");
So, for a asp.net label? You use innerText, or innerHTML.
(or text("your text here") with jQuery)
and with jQuery, you use .value without ()
Try adding ClientIDMode="Static" to your label if that property is available to you. Or you could add ClientID="errLabel" as an alternative. What's happening is asp.net will automatically give your field a generated id for closure on the client side so it will not match your id "errLabel".
<asp:Label runat="server" ID="errLabel" ClientIDMode="Static"></asp:Label>
OR
<asp:Label runat="server" ID="errLabel" ClientID="errLabel"></asp:Label>
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.control.clientidmode?view=netframework-4.8#System_Web_UI_Control_ClientIDMode
I have 2 pages in asp.net with c# .
a parent.aspx and popup.aspx.
I passed a querystring(id) into page load of popup.aspx and used function to call row of table base on id and show gridview on popup.aspx.
now I want to select this row, and pass details into text boxes of parent.aspx that is open now.
Everything is ok and row of table is passed into text boxes, but it is into new window popup of parent.aspx page, that I don't want this.
I want pass details into this page(parent.aspx) that now is open.
How can I do that.thanks.
below is my code for pass id to pop-up window
protected void btn_search_id_Click(object sender, ImageClickEventArgs e)
{
string str1 = Encrypt(txt_sh_p.Text);
btn_search_id.Attributes.Add("onclick", "window.open('popup.aspx?sh_p_=" + str1 + "','Report','width=750,height=500,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,left=200,top=50'); return false;");
}
my code for reading id and select row and display row in gridview on page load event of popup.aspx:
protected void Page_Load(object sender, EventArgs e)
{
DAL.Sab_Ashkh sabt_ashkh = new DAL.Sab_Ashkh();
List<DAL.Sab_Ashkh> sabt_ashkh_list;
sabt_ashkh.sh_p = Decrypt(Request.QueryString["sh_p_"]);
sabt_ashkh_list = sabt_ashkhDB.GetShakh_find(sabt_ashkh.sh_p);
grid_ashkh.Visible = true;
grid_ashkh.DataSource = grid_ashkh_list;
grid_ashkh.DataBind();
}
and html code for pass row to parent page:
<Columns>
<asp:HyperLinkField DataTextField="id_shakh" DataNavigateUrlFields="id_shakh" DataNavigateUrlFormatString="parent.aspx?id_shakh={0}"
HeaderText="id" ItemStyle-Width = "150" />
<asp:TemplateField HeaderText="select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width = "150px" DataField = "sh_p" HeaderText ="kod"
>
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
</Columns>
I am just telling you how you can change the variable in Main page in popup page like:
Suppose Parent.aspx have:
<script type="text/javascript">
var items =[];
</script>
and in popup.aspx you can do something like :
window.opener.items.push(yourSelectedRows);
but as another workaround you can also use local storage like:
localStorage.setItem("selectedRecords", JSON.stringify(selectedRows));
suppose selectedRows are your array of object or anything else but as my experience the selectedRecords would be accessible in all HTML pages.
hope this help you.
Hi Aria Thanks for reply. I pass id by query string into popup window and show gridview . and this script for popup win :
<script type="text/javascript">
function SetName() {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("txt_id_mah");
grid = document.getElementById("grid_ashkh");
var cellPivot;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length; i++) {
cellPivot = grid.rows[i].cells[1];
TXT.value = cellPivot;
}
}
}
window.close();
}
</script>
but does not work.
Can't get value from getValue in JS and can't show value in showValue field.
Thanks in advance
ASPX PAGE CODE
<script>
var x = document.getElementById("<%=getValue.ClientID %>").innerHTML;
document.getElementById('showValue').innerHTML = x;
</script>
<asp:Label runat="server" ID="getValue" />
<asp:Label runat="server" ID="showValue" />
C# CODE
getValue.Text = "value from code";
You need to call javascript once all the controls are rendered, then only you can get the proper id of the <asp:label> control, so you need to write that javascript code under window.onload().
Also for showValue, you need to use ClientID.
window.onload= function(){
var x = document.getElementById("<%=getValue.ClientID%>").innerHTML;
document.getElementById('<%=showValue.ClientID %>').innerHTML = x;
};
I have a small problem . If page is refreshed using F5 , TextBox should preserve its old value . In Page_Load() , if i keep // Loading(); then TextBox1 preserve its old value.
As soon as i remove comment , it loose value in TextBox1 .
Please tell me the reason behind it and What should be done to avoid it .
<script type="text/javascript">
function TextBox1_TextChanged() {
<%
Session["HitCount1"] = TextBox1.Text ;
%>
}
function getMyvalSession() {
var ff = "Loading Value";
return ff;
}
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack='true' onchange="TextBox1_TextChanged()"></asp:TextBox>
<%
string x = null;
x = Session["HitCount1"].ToString().Trim();
if ((x.Equals(null)) || (x.Equals("")))
{
// Session Variable is either empty or null .
}
else
{
TextBox1.Text = Session["HitCount1"].ToString();
}
%>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
// Loading();
}
void Loading()
{
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
}
Combining inline server-side code and code-behind code is generally a bad idea. I would recommend just using the code-behind code.
This code:
function TextBox1_TextChanged() {
<%
Session["HitCount1"] = TextBox1.Text ;
%>
}
... is not going to have the effect of the (server-side) Session entry "HitCount1" getting set to Textbox1.Text, because TextBox1_TextChanged is a client-side function, and your assignment statement is going to happen on the server side. At run time, the chunk of server code will have been removed by the compiler, so TextBox1_TextChanged will be an empty function.
The rule of thumb: Things happen on the client, or they happen on the server on postback, or they happen on the server via Ajax calls. You can't mix client and server code together.
My recommendation: switch to doing everything in code-behind. When you have it working, if you have too many postbacks, investigate Ajax calls.
I have a variable in javascript:
var activeSearchButton = document.getElementById('<%=btnSearch.ClientID %>');
I want to set it like this:
<asp:TextBox ID="WFTo" runat="server" onchange="activeSearchButton = document.getElementById('<%=btnWFSearch.ClientID %>');"></asp:TextBox>
When I am trying to use the varible in javascript function, it is null. And the source shows:
onchange="activeSearchButton = document.getElementById('<%=btnSearch.ClientID %>');"
I noticed '& lt;' instead of "<". Is this the reason of my problem? Why does this happen? Or maybe there is another reason?
Thank you very much.
Just create a function in <script /> section
function setActiveSearchButton()
{
activeSearchButton = document.getElementById('<%=btnSearch.ClientID %>');
}
and use
<asp:TextBox ID="WFTo" runat="server" onchange="setActiveSearchButton()"></asp:TextBox>
EDIT:
As it turns out, you cannot use <%= .. %> for server side controls. You'll have to resolve to using a regular html input like this
<input type="text" onchange="setActiveSearchButton('<%= btnSearch.ClientID %>')" />
and
function setActiveSearchButton(buttonId)
{
activeSearchButton = document.getElementById(buttonId);
}
or leave the <asp:TextBox /> as it is and on Page_Load do
protected void Page_Load(object sender, EventArgs e)
{
WFTo.Attributes.Add("onchange", "setActiveSearchButton('" + btnSearch.ClientID +"')");
}
You can do this:
onchange='<% = string.Format("activeSearchButton = document.getElementById(\"{0}\");", btnWFSearch.ClientID) %>'
EDIT: As our friend said, we can only do this in a "input" control. For a TextBox the best way is add a parameter in codebehind.