DIV content inside Repeater not controllable - javascript

Inside a repeater's ItemTemplate, I have..
retstr.AppendLine("<div id='contentDivImg' style='display: block;'><img src = '" & img_src & "' /></div>")
Every image needs to hide and show when the toggle button/link is pressed. Although, only the first IMAGE/DIV toggles visibility, none of the following images whose paths are also gotten from the database by the line of code above. Why? I've tried using class instead of id parameter.
Here is the javascript only if interested..
<script type="text/javascript">
function toggle(showHideDiv, switchImgTag) {
var ele = document.getElementById(showHideDiv);
var imageEle = document.getElementById(switchImgTag);
if (ele.style.display == "block") {
ele.style.display = "none";
imageEle.innerHTML = '<img src="/images/Show.png">';
}
else {
ele.style.display = "block";
imageEle.innerHTML = '<img src="/images/Hide.png">';
}
}
</script>
And, here is the simple toggle link to show and hide the conntentDivImage when clicked..
<a id="imageDivLink" href="javascript:toggle('contentDivImg', 'imageDivLink');"><img src="/images/Hide.png"></a>

getElementById only returns the first element by that ID, and so therefore the 1st one is the only one that is going to work according to your code. I would add a counter for use in your ItemTemplates to give each div a unique ID, like contentDivImg1 and contentDivImg2, and then when you have the ItemTemplate for the anchor tag, make sure to reference the right one when calling your javascript function.

The problem is that, in HTML, IDs are meant to be unique. document.getElementById() stops after finding the first element with a matching ID. In this case, it finds the first <div> and ignores the rest of the page.
However, you can change the way that you use your repeater to better suit your needs:
If you restructure your repeater to look more like this:
<!-- the repeater now has an OnItemDataBound event -->
<asp:Repeater runat="server" ID="rptDivs" OnItemDataBound="rptDivs_OnItemDataBound">
<ItemTemplate>
<!-- The <div>, <img>, and <a> tags have runat="server". This is important. -->
<div runat="server" ID="div"><img runat="server" ID="img" />
<a id="a" runat="server"><img src="/Images/Hide.png" id="img2" runat="server" /></a>
</div>
</ItemTemplate>
</asp:Repeater>
...then each <div> and <img /> within the repeater will have a unique id. The ID will look something like this: ``.
You will need to add an event to your page's code behind to set the properties (such as src) for your HTML. Since you've added the OnItemDataBound event to the repeater, you can access the objects in your code behind (this is in C#, but the idea will still work in VB).
protected void rptDivs_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
// first, let's get the item that you have bound to your repeater
MyObject myObject = (MyObject)e.Item.DataItem;
// You can access the image and div objects here because they are set to runat="server"
HtmlImage img = (HtmlImage)e.Item.FindControl("img");
HtmlImage buttonImg = (HtmlImage)e.Item.FindControl("img2");
HtmlAnchor a = (HtmlAnchor)e.Item.FindControl("a");
HtmlGenericControl div = (HtmlGenericControl)e.Item.FindControl("div");
// you can now set the properties of the HTML in your code-behind
img.Src = myObject.imgSrc;
a.Attributes["onclick"] = "javascript:toggle('" + div.ID + "', '" + buttonImg.ID + "');";
}
The HTML output of each repeated element might now look something like this:
<div ID="body_body_div_1"><img ID="body_body_img_1" />
<a id="body_body_a_1" onclick="javascript:toggle('body_body_div_1', 'body_body_img_1');"><img src="/Images/Hide.png" id="body_body_img2_1" runat="server" /></a>
</div>
...with the ID's changing between each repeated element.

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 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>

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

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

Javascript parse html, modify anchor tags that contain images

I have a vague idea on howto do this but I hoped more experienced devs might have a simpler solution.
I have a sting of HTML code from a JSON feed and where an "a" tag exists with an images inside the "a" tag I want to modify and add attributes. example:
<a style="color:000;" href="images/image.jpg">
<img width="100" height="20" src="images/image_thumb.jpg" />
</a>
I would like to change it to be:
<a style="color:000;" href="images/image.jpg" rel="lightbox" >
<img width="100" height="20" decoy="images/image_thumb.jpg" />
</a>
So adding an attribute to the "a" tag and modifying an attribute in the "img" tag. There maybe multiple links within the HTML code some with and without images and other HTML code surrounding them.
To be clear this is NOT modifying HTML already rendered on the page, this is modifying a string of code before it gets rendered.
To be extremely clear here is the JSON feed in question: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json
The HTML code that contains the tags are found at "feed > entry > content > $t"
Am currently working with Mootools 1.3
Any ideas? Thanks.
First, put it in a new element that does not exist on the page, then modify it as usual:
var container = new Element("div", { html: yourHTML });
container.getElements("a img").forEach(function(img){
var link = img.getParent("a");
img.decoy = img.src;
img.removeAttribute("src");
link.rel = "lightbox";
});
Demo here: http://jsfiddle.net/XDacQ/1/
In straight JS
var a = document.createElement('div');
// put your content in the innerHTML like so
a.innerHTML = '<a style="color:000;" href="images/image.jpg"><img width="100" height="20" src="images/image_thumb.jpg" /></a>';
var b = a.firstChild;
b.rel = 'lightbox';
var c = b.firstChild;
c.setAttribute('decoy', c.src);
c.src = null;
// now you have your a tag
var newA = a.innerHTML;
Dumbest regexp
var string = '<a style="color:000;" href="images/image.jpg">="images/image_thumb.jpg" /></a>',
text = '';
text = string.replace('href', 'rel="lightbox" href');
text = text.replace('src', 'decoy');

Categories