How can I change the display property of my server side label to Block?
<asp:Label id="lblError" runat="server" style="display:none;"></asp:Label>
function block()
{
// change display property to block
}
I tried
document.getElementById('lblError').style.display = "block";
but it's not working, please help me.
use ClientIDMode :
<asp:Label id="lblerror" runat="server" ClientIDMode="Static" style="display:none;"></asp:Label>
and in client:
document.getElementById('lblerror').style.display = "block";
Should be:
document.getElementById('lblError').style.display = "block";
Or you can use a safer way:
var buttonID = '<%= lblError.ClientID %>';
var button = document.getElementById(buttonID);
if (button) {
button.style.display = 'block';
}
It also looks like youv'e missed a double quote after style=. It should be :
<asp:Label id="lblError" runat="server" style="display:none;"></asp:Label>
One way to access a control from client script is to pass the value of the ClientID property of the server control to the document.getElementById method. Like this:
document.getElementById('<%= lblerror.ClientID %>').style.display = "block";
Have a look at this: How to: Access Controls from JavaScript by ID.
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 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'}]">
In my project i need change visible of dynamic asp control when click label based on textbox values. So i first tried to get textbox value when click label but its return undefined. I am search and get two methods i tried that also it return same.
My Try :
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$(document).on("click", "#lblShow", function() {
alert($('#<%=txtTotalVersion.ClientID%>').val());
alert($('input[id$=txtTotalVersion]').val());
var xTotlal =$('#<%=txtTotalVersion.ClientID%>').val()
var i = 0;
for (i = 0; i < xTotlal; i++) {
$('#createDiv' + i).style.display = "blcok";
$('#createDiv1' + i).style.display = "block";
$('#createDiv2' + i).style.display = "block";
$('#createDiv3' + i).style.display = "block";
}
});
});
</script>
HTML
<div id="DivCompName">
<asp:TextBox runat=server ID="txtTotalVersion" Visible="false"></asp:TextBox>
<asp:TextBox runat=server ID="txtCurrentDisplay" Visible="false"></asp:TextBox>
</div>
First two alert return undefined.
Visible="false" is asp.net attribute, in this case your control will not be rendered at the client side. So your client script won't find the control as it doesn't exists!
If you want to store some value at client side and don't want to display it then you can use HiddenFields or you can make the same control hidden by using css style display:none;. (Don't use Visible="false" for this)
you can add ClientIDMode=Static and call it from your jquery
<asp:TextBox runat=server ID="txtTotalVersion" Visible="false" ClientIDMode="Static"></asp:TextBox>
<script>
$(document).ready(function () {
alert("#txtTotalVersion").val();
})
</script>
reason is, the client id for your control might not be as it is assigned with ID="xxx", if the control is inside of another asp.net server control, after adding the ClientIDMode, you are telling your server to treat this control with a static ID
to learn more: msdn
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 am trying to hide a data field if it is null via ASP.NET.
I have the following setup:
<script runat="server" type="text/vb">
// target the id called test
var test = document.getElementById("test");
// if test is not empty, show
// else hide test
if (test.value != null){
document.getElementById("test").style.visibility = visible;
}else{
document.getElementById("test").style.visibility = hidden;
}
<p><asp:Label runat="server" id="test"><%# Eval("DBField")%></asp:Label></p>
Am I way off here? I am getting error in whatever I try. I don't think it should be so complicated however...any thoughts/recommendations would be greatly appreciated.
Thank you in advanced,
Without knowing what your error is it's hard to give you an answer. One thing that jumps out is that you are not using the ClientId of the asp.net control. Try changing this:
var test = document.getElementById("test");
to this:
var test = document.getElementById("<%=test.ClientID%>");
When you assign an ID to an asp.net control, that is not the ID that gets rendered. Give this article a read for more info on that.
There are a few possible issues here:
Since you are using a server control, depending on what its parent is, the ASP.NET runtime could be changing its ID. If you View Source on your page it may show an ID like "ctl00_main_test" or something similar. To get aroud this you have to do the followinh:
var test = document.getElementById("<%= test.ClientID %>");
if (test.text != null){
test.style.visibility = 'visible';
}else{
test.style..visibility = 'hidden';
}
Since "visibility" maps to a CSS style, you probably have to use quotes around "visible" and "hidden"
Lastly, getElementByID should work well for all modern browsers, but older browsers could have flaky implementations. I suggest looking at jquery to simplify this code:
if ( $('#<%=test.ClientID>').text() != '' && $('#<%=test.ClientID%>').text() != null){
$('#<%=test.ClientID%>').show();
}else{
$('#<%=test.ClientID%>').hide();
}
You need to test against empty string in JavaScript, like this:
var test = document.getElementById("<%=test.ClientID%>");
if (test){
test.style.visibility = (test.value == "" ? "hidden" : "visible");
}
EDIT
I just noticed that you're using databinding syntax, which makes me think that this Label is inside of a grid or something. You can try something like this instead:
<asp:Label ID="test" runat="server" Visible='<%#(String.IsNullOrEmpty(Eval("DBField")) == false)%>'><%#Eval("DBField")</asp:Label>
I was able to hide data via the following code:
<asp:PlaceHolder ID="PlaceHolder" runat="server" Visible='<%# IIf((Eval("test")).ToString().Length > 0, "true", "false") %>'>
<h3>test</h3>
<asp:Label ID="test" runat="server" Text='<%# Bind("test") %>'></asp:Label>
</asp:PlaceHolder>
Span tags do not have a value:
if ($('#<%=test.ClientID%>').html() != "") //jQuery
or
if (document.getElementById("<%=test.ClientID%>").innerText != "")