Show/Hide Database Field based on Null/Not Null ASP.NET - javascript

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 != "")

Related

How to change the value of an asp label with JavaScript?

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

Asp.Net Control Value return undefined in Jquery

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

How to change a server side label display to Block in javascript?

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.

How to get active tab index from TabContainer

Currently I am using this line of code in my JavaScript
var tabIndex = $(':focus').attr('tabIndex');
However this constantly fails to get the active index.
Here is asp:TabContainer header in case this helps. I have also tried document.GetElementById, however to no avail as well.
<asp:TabContainer ID="AdvOrBasicSearch" runat="server" ActiveTabIndex="0">
They say a picture is worth a thousand words...
I have used jQuery here. With it it is simple to find what you want. Pay attention to the rectangled text in the pic.
Happy coding.
I found this method works much better. I created a variable with the tabContainer itself. Then, I just needed to go inside the variable and pull the value from the _activeTabIndex property.
var tabIndex = $find("AdvOrBasicSearch"); //AdvOrBasicSearch is name of tabContainer
var i = tabIndex._activeTabIndex;
Get tab index and tab name using javascript
< script type="text/javascript">
function onTabChanged(sender, e) <br> { <br>
var curIndex = document.getElementById('lblCurTabNo');<br>
var curName = document.getElementById('lblCurTabName');<br>
curIndex.innerHTML = sender.get_activeTabIndex();<br>
curName.innerHTML = sender.get_activeTab().get_headerText();<br>
}<br>
< /script><br><br>
< asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0" UseVerticalStripPlacement="false"
Width="400px" BackColor="ActiveBorder" ForeColor="Green" OnClientActiveTabChanged="onTabChanged"><br>
----asp tab control-----------
< /asp:TabContainer>
Tab Index : < asp:Label ID="lblCurTabNo" runat="server" Text="0"></asp:Label><br />
Tab Name :< asp:Label ID="lblCurTabName" runat="server" Text="Personal Info"></asp:Label>

How to use Javascript to get ASP.NEt Web Forms label's value?

I have the following label control:
<asp:Label ForeColor="DarkGreen" runat="server" ID="lblStatus"></asp:Label>
Its value is filled in the Page_Load event.
I attached the following Javascript (placed at the end of the page, not Master page):
function Validate() {
var lblObj = document.getElementById('<%=lblStatus.ClientID%>');
alert(lblObj.value);
if (lblObj.value == "Replaced" || lblObj.value == 'Trashed' || lblObj.value == "Internal Use") {
alert("Products with" + lblObj.value + "status cannot be reserved");
return false;
}
}
The alert(lblObj.value) displays a popup with text "undefined". How can I fix this problem? Please, I tried many combinations for placing the JavaScript but no luck! Thanks
UPDATE
Browser soruce code:
<span id="ctl00__main_lblStatus" style="color:DarkGreen;">Available</span></td>
First line of Validate JS function:
function Validate() {
var lblObj = document.getElementById('ctl00__main_lblStatus');
labels don't have a value. They have innerHTML and innerText.
Use JQuery and it will run in all browsers and platforms, something like:
$('#<%= lblStatus.ClientID %>').next().text();
source: JQuery: getting the value/text/innerHtml of a checkbox in an ASP.NET CheckBoxList control
Label server control renders as span. So you should get it's content by innerText. try this :
alert(lblObj.innerText);
ASP.NET label server control will be rendered in complex HTML output.
Like:
<span id="ctl00_ctl00_ContentPlaceHolder1_BodyPlaceHolder_lblLanguage0">
<label class="inputText">English</label>
</span>
When you use getElementById you will get span.
But to set value via javascript you have to access inner label object
try this
<script language="javascript" type="text/javascript">
function getlabelvalue()
{
var value1 = document.getElementById('<%=labelID.ClientID%>').value;
if (value1.length < 1)
value1 = 0;
}
</script>
With jquery you need to use the html method.
var g = $('#<%=lblStatus.ClientID%>').html();
These will NOT work with jquery:
$('#<%=lblStatus.ClientID%>').innerText
$('#<%=lblStatus.ClientID%>').innerHTML
$('#<%=lblStatus.ClientID%>').val()

Categories