getElementById succeeds once then returns null - javascript

I'm new to javascript and this is driving me nuts.
I'm attempting to set the text and color of a label ("lblerrmsg") depending upon the value of a flag ("IsValid"). I've written a function in a .js file and have attached it to web site that I built with VS.
The function - specifically getElementById('lblErrMsg') works correctly the first time it is called, but in subsquent calls it returns null. (Don't know if this is relevant - but there are no posts between calls to the function.)
Following is the relevant portion of the function:
// If IsValid is false - make the text red
var ErrMsg = document.getElementById('lblErrMsg');
if (IsValid) {
document.activeElement.style.color = 'navy';
ErrMsg.outerHTML = 'valid';
}
else {
document.activeElement.style.color = 'red';
ErrMsg.outerHTML = "*** Invalid Entry ***";
ErrMsg.style.color = 'red';
}
<asp:TextBox ID="tbNumber" runat="server"></asp:TextBox>
<asp:Label ID="lblErrMsg" runat="server" ForeColor="Red"
Text=" xxx" ></asp:Label>

ErrMsg.outerHTML = 'valid';
If you do that, you have destroyed the previous ErrMsg and the new content will not have the id anymore (so that it cannot be found by getElementById).
Are you sure you don't want innerHTML?

try to change the class name of the div or element to change the css style if you want
document.getElementById("blah").className = "cssclass";
this way you can control the css depending on the flag of yours.

Related

changing the textbox text to xxxx after tabbing out of it

I have a textbox that takes social security number. I have a requirement to change the first 5 numbers of social security number to X's once the user tabs out of that field so if the user enters
123456789
the number should become XXXXX6789
I tried doing it using txtSSN_TextChanged event, but that causes a postback. Can I do something like this in Javascript or Jquery. Below is my C# code:
string lastFourSSN = "";
lblHidden.Text = txtssn.Text.ToString().Replace("-", "");
lastFourSSN = Utility.Encode.GetLast(lblHidden.Text.ToString(), 4);
txtssn.Text = "XXX-XX-" + lastFourSSN;
It is a certainly a great idea on your part. jQuery will do the trick here.
First up, you can wire in a client side event and then turn auto-postback for that text box off (and likely you already did, since you note you never wanted a post-back for such a little task).
Ok, so your standard text box will look like this:
<asp:TextBox ID="TextBox1" runat="server"
onchange="mychange();" Width="280px" ClientIDMode="static" ></asp:TextBox>
I did add ClientIDMode static, it just makes the js more friendly to pick up the control.
And the "onchange" event is really the same as the server side post-back and change event (but of course client side).
So, our js? this works:
<script>
function mychange() {
var txt1 = $('#TextBox1');
s = txt1.val();
if (s.length > 5) {
s = "XXXXX" + s.substring(s.length - 4, s.length);
txt1.val(s);
}
}
</script>
There is no handy "right" function in js, or jQuery. But you can tweak the above a bit.
Note that substring is 0 based.
You could perhaps tweek the above. You could even remove the "if" in above, but the above quite much is a good base starting point.

ADF Display Image Based on OutputText Value

In my ADF application, the value in #attachmentTxt element returns the attachment value from the service/DB as a boolean value. I am trying to display the activeImage object if the value returns true and to just display blank if it's false. I am limited to the use of standard Javascript, no externals such as jQuery.
<af:outputText id="attachmentTxt" value="#{bean.attachment}" visible="false" />
<af:activeImage id="attachmentImg" source="/images/icon.png"></af:activeImage>
a non-working example for what I'm looking for is:
<af:resource type="javascript">
function hasAttachment() {
var att = document.getElementById("attachmentTxt");
var attImg = document.getElementById("attachmentImg");
if(att.value == 'true') {
attImg.show();
} else {
attImg.hide();
}
}
</af:resource>
Thank you in advance
in my opinion you should use the "rendered" attribute of the activeImage tag to decide whether to display the image or not. So it is not necessary to use JavaScript. The ADF Framework will only render the image if the value is true.
<af:activeImage id="attachmentImg" source="/images/icon.png" rendered="{#bean.attachment}"></af:activeImage>

How to toggle the visibility of a document element?

I have a label on my form like so:
<asp:Label ID="lblPwPol"
runat="server"
Visible="false">
A bunch of text...
</asp:Label>
In a method called by the Page_Load event (VB.net), I attach some JS event handlers with this:
btnPasswordPolicies.Attributes.Add("onClick", "return mShowToolTip();")
cmdPasswordPolicies.Attributes.Add("onmouseleave", "return mHideToolTip();")
Which are defined as such:
function mShowToolTip(aCtrl, aArg1)
{
document.getElementById("lblPwPol").style.display = 'block';
return false;
}
function mHideToolTip()
{
document.getElementById("lblPwPol").style.display = 'none';
return false;
}
When my form loads, the label is not visible (correct).
When I click the label, I get an exception in my JS:
Javascript runtime error: Unable to get property 'style' of undefined or null reference
Which obviously means that document.getElementById("lblPwPol") returns null.
Any idea what I'm doing wrong? I feel like it's got to be something rally stupid, but I don't know JS at all.
I tried also switching out the id="lblPwPol" to be name="lblPwPol" instead, but that didn't make a difference.
First thing you should remove visible="false" to the label, because of you make it visible false it won't load in Dom. And keep style="display:none"
Like this
<asp:Label ID="lblPwPol"
runat="server"
Style="display:none">
A bunch of text...
</asp:Label>
I think you are confusing DOM elements with ASP WebUI WebControl elements (that are XML as well btw). Take a look at here how to access a Label control like yours: How to access asp:label text property from code behind?

How can I get the text from an Asp.Net TextBox control with Jquery or Javascript?

I have an Asp.Net TextBox control:
<asp:TextBox ID="txtFromDate" runat="server" CssClass="txtDateFrom"></asp:TextBox>
In a separate Jquery/Javascript file, I would like get the text from it... normally the text is like '9/1/2015'.
I have tried the following:
var r2FromDate = new Date($(".txtFromDate").val);
var r2FromDate = new Date($(".txtFromDate").val.toString());
var r2FromDate = new Date($(".txtFromDate").val());
var r2FromDate = new Date($(".txtFromDate").text());
var r2FromDate = new Date($(".txtFromDate").text);
and the same with using the # <%= txtFromDate.ClientID %> notation and it completely breaks with that.
Please help!
$('#txtFromDate').val();
You want to select using the ID, not the class.
var text = $("#<%=txtFromDate.ClientId %>").val();
ASP should then output the ID generated on the client and your javascript can select it. You can also reuse this variable instead of querying the DOM over and over [it has to find it every time you use jQuery like "$(...)"].
If your javascript is located in another file, you can use the name attribute instead
<asp:TextBox ID="txtFromDate" runat="server" CssClass="txtDateFrom" name="txtFromDate"></asp:TextBox>
$('input[name="txtFromDate"]').val();
https://api.jquery.com/attribute-equals-selector/
Alternatively, you can define the following property on your TextBox
ClientIDMode="static"
That will ensure that your ID on the client side will be the same as the server side id.
And then you can use:
$('#txtFromDate').val();
It was actually because I put the id as 'txtFromDate' and the class as 'txtDateFrom' instead of keeping them the same. I was trying to access the class 'txtFromDate' when it didn't exist.
.val() works when you select the right class.
You can try this through this you can also get asp button or any control for that matter.
var txt_txtFromDate = document.querySelector("input[id*='txtFromDate']");
alert(txt_txtFromDate.Value);
you can also try querySelectorAll() if you have multiple controls with same id in client side.
Also, $("input[id*='txtFromDate']") will work.

Passing ClientId of a textbox to use it in a javascript function

this is my control:
<asp:TextBox ID="txt_rol" onkeyup="this.value=this.value.toUpperCase()" runat="server" BorderColor="#E0E0E0" BorderStyle="Solid" Width="240px"></asp:TextBox>
</strong>
<asp:ImageButton ID="imgBtnGuardar" runat="server" ImageUrl="~/imagenes/boton.guardar.jpg" OnClientClick="ValidaCajadeTextoVacia(document.getElementById('<%=txt_rol.ClientId%>'));MensajeCargandoJQUERY();"/>
The problem is, that i can't get the Id of the textbox.
Well, right off the bat I can tell you that there's a syntax issue in the code. It should be:
'<%= txt_rol.ClientID %>'
There may be other obstacles you need to overcome here too. For example, if these controls are nested in a GridView you won't be able to reference the control that way.
function masterClick(clicked, controlID) {
var dynCtrl = clicked.id.substring(0, clicked.id.lastIndexOf("_") + 1);
var tBox = document.getElementById(dynCtrl + controlID);
tBox.value = "";
tBox.focus();
}
Then call from your image button like...
masterClick(this,'txt_rol');
change tBox.value and focus to whatever action you like, but should have access to the control in JavaScript now. You can add in a check like " if (tBox) " to ensure you have an object. The downside is the static reference to the control within the inline javascript, and you have to adjust when the calling control is in a different container, grid, panel, etc.
Check the output with View Source and you will understand what is happening. You'll have to set the OnClientClick property server-side (onload). Or find a way to bind it OnClientClick='<%#SomeProperty%>'.
Another option could be to use jQuery to find your control:
$("input:text[id*=txt_rol]")
By the way: your JavaScript won't work if someone pastes in the textbox using the mouse (right-click/paste).

Categories

Resources