Simply, I have an anchor inside a repeater that triggers on click a javascript function, which sets the innerHTML of a Div to some content.
trying this outside a repeater did work!
but if I tried to implement the same code in the repeater's item template, it won't work!
NOTE: I think I need to access the repeater first then access the Anchor inside it! but I don't know how to do it
For further illustration:
JavaScript Function:
function show(ele, content) {
var srcElement = document.getElementById(ele);
if (srcElement != null) {
srcElement.innerHTML = content;
}
}
The repeater's code:
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
Name : <%# Eval("name")%>
<DIV ID= "PersonalInfo1" runat="server"></DIV>
<A id="A1" href="#" runat="server" onclick="show('PersonalInfo1','Address : ')">More...</A>
</ItemTemplate>
</asp:Repeater>
PS: THE POSTED CODE ISN'T WORKING IN THE REPEATER!
That is because id's are unique. Select elements using getElementsByName or by their class name with for example jQuery.
OK... let's start over.
Have such repeater code:
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<div>
Name : <%# Eval("name")%>
<div id="Address" runat="server" style="display: none;"><%# Eval("address")%></div>
<div id="Interests" runat="server" style="display: none;"><%# Eval("interests")%></div>
<a id="A1" href="#" runat="server" onclick="return show(this, 'Address');">Show address</a>
<a id="A2" href="#" runat="server" onclick="return show(this, 'Interests');">Show interests</a>
</div>
</ItemTemplate>
</asp:Repeater>
Then such JavaScript code:
function show(oLink, targetDivID) {
var arrDIVs = oLink.parentNode.getElementsByTagName("div");
for (var i = 0; i < arrDIVs.length; i++) {
var oCurDiv = arrDIVs[i];
if (oCurDiv.id.indexOf(targetDivID) >= 0) {
var blnHidden = (oCurDiv.style.display == "none");
oCurDiv.style.display = (blnHidden) ? "block" : "none";
//oLink.innerHTML = (blnHidden) ? "Less..." : "More...";
}
}
return false;
}
This will search for "brother" DIV element of the clicked link, and show or hide it.
The code is as simple as possible using pure JavaScript, you should be able to understand what each line is doing - feel free to ask if you don't. :)
Note, you have to put the personal info in the PersonalInfo div in advance instead of passing it to the function - the function will get pointer to the clicked link.
Yes you need to iterate all the relevant links. Solution that involve minimal change of code is adding class to the links then check for this class:
<A id="A1" href="#" runat="server" class="RepeaterLink" ...>
And then in JavaScript:
var arrLinks = document.getElementsByTagName("a");
for (var i = 0; i < arrLinks.length; i++) {
var oLink = arrLinks[i];
if (oLink.className == "RepeaterLink") {
//found link inside repeater..
oLink.click();
}
}
This will "auto click" all the links, you can check ID or something else to imitate click of specific link in the repeater as well.
Related
I'm having trouble trying to clear these banking and routing numbers that are in a textbox on an aspx page. I've seen it used where they would just specify the ID of the textbox and do a textbox.text = String.Empty(). But that doesn't seem to work here. Maybe I'm using the wrong ID?? I also tried using JQuery .val("") but that didn't seem to work either.
Here's the code, i'd like to clear both Routing and Account text fields on click of a button:
<div id="DivUser1BankInfo" class="labelAndTextboxContainer">
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelRoutingNumber" runat="server" Text="Routing #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextRoutingNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankRoutingNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelAccountNumber" runat="server" Text="Account #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextAccountNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankAccountNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<button type="button" id="clearButton1">Clear</button>
<div class="button">
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' OnClick="clearFields_btn"/><br />
</div>
The OnClick= "clearFields_btn" code behind =
protected void clearFields_btn(object sender, EventArgs e)
{
}
Thanks for any help!
I haven't worked with ASP.NET in a little while, but I think you may want the OnClientClick event, not OnClick. OnClientClick is for client-side code (your jQuery/JavaScript) and OnClick is for server-side code (your C# or VB.NET).
You'd also want your OnClientClick event method to return false, or the server-side code will also fire.
So I think you want something like:
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>
OnClientClick="clearText();"/>
And then clearText would look like this:
<script>
function clearText()
{
//our two IDs
$('input[id*="User1TextRoutingNumber"]').each(function(index) {
$(this).val('');
});
$('input[id*="User1TextAccountNumber"]').each(function(index) {
$(this).val('');
});
return false;
}
</script>
EDIT: shoot, I see my mistake. Fixed the code to clear the text of the textbox, not the button ("this").
Edit: removed the space from the "clear" text val.
EDIT: Made search a little more flexible, less dependent on GridView or no GridView.
Try this
<script>
var clear = function(textboxID){$('input[id*=' + textboxID + ']').val('');};
return false;
</script>
<button id="btClearText" onclick="javascript:return clear('txtName');">
but if you need a more specific answer then please post more information
You need something like this. Assuming you want a client side solution (not very clear from your question).
<script type="text/javascript">
function clearTextBox() {
document.getElementById("<%= User1TextRoutingNumber.ClientID %>").value = "";
//or
$("#<%= User1TextRoutingNumber.ClientID %>").val("");
}
</script>
The <%= User1TextRoutingNumber.ClientID %> will ensure you get the correct ID for javascript/jQuery.
A server side solution would be:
protected void clearFields_btn(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox tb = GridView1.Rows[i].FindControl("User1TextAccountNumber") as TextBox;
tb.Text = "";
}
}
I have a list of activities that is displayed with a Repeater. I already use Timers to display these, so the Timer isn't the problem. It's the code that i have to put into the Timer_tick method.
The "highlight-Timer" is supposed to highlight the items/rows one at a time, and then I want to display some info related to the highlighted row.
If it's easier with another control that's no problem. I doesn't have to be a Repeater. I just use it because of the styling-possibilities (it isn't displayed in just one line, but with several line-breaks etc.)
As requested:
(Repeater)
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div id="divActivity" runat="server">
<span style="font-size:30px;">
<%# DataBinder.Eval(Container.DataItem, "act_headline") %>
</span>
<br />
<img alt="mapIcon" src="../img/mapIcon.gif" height="15px" width="15px" style="position:absolute;" />
<span style="font-size:12px; font-style:italic; margin-left:23px;">
<%# DataBinder.Eval(Container.DataItem, "act_place") %>
</span>
<img alt="watchIcon" src="../img/watchIcon.png" height="15px" width="15px" style="position:absolute;" />
<span style="font-size:12px; font-style:italic; margin-left:23px;">
<%# DataBinder.Eval(Container.DataItem, "act_start") %> - <%# DataBinder.Eval(Container.DataItem, "act_end") %>
</span>
<br />
<div style="word-wrap: break-word; width:1000px; margin-top:20px; padding:0;">
<%# DataBinder.Eval(Container.DataItem, "act_text") %>
</div>
<br />
<img alt="infoIcon" src="../img/infoIcon.png" height="15px" width="15px" style="position:absolute;" />
<span style="font-size:12px; margin-left:23px;"><a target="_blank" href="http://<%# DataBinder.Eval(Container.DataItem, "act_info") %>"><%# DataBinder.Eval(Container.DataItem, "act_info") %></a>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
I don't have anything in the the Timer_tick-event, as i've tried several things and the deleted it after it failed. Hope it's enough.
I would set a special CSS class to the highlighted item by using something like this in the tick event handler by looping over the Repeater.Items collection.
Something like this (untested):
int currentHighlight = -1;
int nextHighlight = -1;
for (int i = 0; i < Repeater1.Items.Count; i++)
{
HtmlControl htmlDiv = (HtmlControl)Repeater1.Controls[i].Controls[1];
if (htmlDiv.Attributes["class"] != null)
{
if (htmlDiv.Attributes["class"].Contains("highlighted")) // this is the currently highlighted item
{
// record currently highlighted item index
currentHighlight = i;
// remove highlight
htmlDiv.Attributes["class"].Replace("highlighted", "");
htmlDiv.Attributes["class"].Trim();
}
}
}
if ((currentHighlight == -1) || (currentHighlight == Repeater1.Items.Count))
{
// handle first Item highlighting
nextHighlight = 1;
}
else
{
// handle standard case
nextHighlight = currentHighlight + 1;
}
// highlight next item
((HtmlControl)Repeater1.Controls[nextHighlight].Controls[1]).Attributes["class"] += " highlighted";
Then you can use the highlighted CSS class to handle styling (the bold font you mention) as well as some special behavior in JavaScript or jQuery for example.
BTW, you can do any other operation on the RepeaterItem object once you get which one is currently highlighted.
I have a div inside an asp:Repeater:
<ItemTemplate>
<div id="myDiv" style="display:none" />
</ItemTemplate>
</asp:Repeater>
<script type="text/javascript">
window.onload = function() {
document.getElementById('myDiv').style.display = 'block';
</script>
This works great except my div elements occur within a repeater which means only the first div is found. Could some please explain to me how to get all the divs in the ItemTemplate?
It is invalid to use the same id more than once on a page. Instead you'll have to use some other means of finding your elements, such as css class. jQuery makes this task easy.
$(".someClass").show();
However, you may not even need to do that. If all you are trying to do is change some styles on a set of elements under a common parent, you can just change the class name of the parent. Consider the following repeater:
<div id="repeaterParent">
<asp:Repeater runat="server">
<ItemTemplate>
<div class="repeaterItemDiv"></div>
</ItemTemplate>
</asp:Repeater>
</div>
Set up your css like this:
#repeaterParent .repeaterItemDiv
{
display: none;
}
#repeaterParent.showDivs .repeaterItemDiv
{
display: block;
}
Then use this JavaScript:
document.getElementById("repeaterParent").className = "showDivs";
Or, this jQuery:
$("#repeaterItemParent").addClass("showDivs");
You can't have multiple elements with the same ID value on the page. Use classes instead:
<ItemTemplate>
<div class="myDiv" style="display:none" />
</ItemTemplate>
Selecting the DIVs:
document.getElementsByClassName('myDiv')
// or
document.querySelectorAll('.myDiv')
// or
$('.myDiv') // jQuery
If you want to do this in javascript, you can do something like the following:
<div id="repeaterParent">
<asp:Repeater runat="server">
<ItemTemplate>
<div id="myDiv" style="display:none" runat="server"/>
</ItemTemplate>
</asp:Repeater>
</div>
<script type="text/javascript">
window.onload = function(){
//get the parent element
var ParentEle=document.getElementById('repeaterParent');
//get all the div tags within parent element
var AllDivInParentEle=ParentEle.getElementsByTagname('DIV');
//loop div elements and do what is required
for(var i=AllDivInParentEle.length-1;i>=0;i--){
AllDivInParentEle[i].style.display = 'block';
}
}
</script>
Using runat="server" for the div will give it its own id.
But if the div does not need to have an id, the javascript method will still work as it relies on the parent elements id.
So you could replace
<div id="myDiv" style="display:none" runat="server"/>
with
<div style="display:none">
I have been trying to set the value of a hidden input by using Javascript and then access the value from within my C# codebehind. When I run the code that is copied below, the value that is assigned to assignedIDs is "", which I assume is the default value for a hidden input. If I manually set the value in the html tag, then assignedIDs is set to that value.
This behavior suggests to me that the value of the input is being reset (re-rendered?) between the onClientClick and onClick events firing.
I would appreciate any help with the matter. I have spent hours trying to solve what seems like a very simple problem.
html/javascript:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Admin Page - Manage Tasks</title>
<script language="javascript" type="text/javascript">
function PopulateAssignedIDHiddenInput() {
var source = document.getElementById('assignedLinguistListBox');
var s = "";
var count = source.length;
for (var i = count - 1; i >= 0; i--) {
var item = source.options[i];
if (s == "") { s = source.options[i].value; }
else { s = s.concat(",",source.options[i].value); }
}
document.getElementById('assignedIDHiddenInput').Value = s;
// I have confirmed that, at this point, the value of
// the hidden input is set properly
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel id="EditMode" runat="server">
<table style="border: none;">
<tr>
<td>
<asp:Label ID="availableLinguistLabel" runat="server" Text="Available"></asp:Label><br />
<asp:ListBox ID="availableLinguistListBox" runat="server" Rows="10" SelectionMode="Multiple"></asp:ListBox>
</td>
<td>
<input type="button" name="right" value=">>"
onclick="Javascript:MoveItem('availableLinguistListBox', 'assignedLinguistListBox');" /><br /><br />
<input type="button" name="left" value="<<"
onclick="Javascript:MoveItem('assignedLinguistListBox', 'availableLinguistListBox');" />
</td>
<td>
<asp:Label ID="assignedLinguistLabel" runat="server" Text="Assigned To"></asp:Label><br />
<asp:ListBox ID="assignedLinguistListBox" runat="server" Rows="10" SelectionMode="Multiple"></asp:ListBox>
</td>
</tr>
</table>
//-snip-
<asp:Button ID="save_task_changes_button" runat="server" ToolTip="Click to save changes to task"
Text="Save Changes" OnClick="save_task_changes_button_click" OnClientClick="Javascript:PopulateAssignedIDHiddenInput()" />
</asp:Panel>
<!-- Hidden Inputs -->
<!-- Note that I have also tried setting runat="server" with no change -->
<input id="assignedIDHiddenInput" name="assignedIDHiddenInput" type="hidden" />
</div>
</form>
</body>
c#
protected void save_task_changes_button_click(object sender, EventArgs e)
{
string assignedIDs = Request.Form["assignedIDHiddenInput"];
// Here, assignedIDs == ""; also, Request.Params["assignedIDHiddenInput"] == ""
// -snip-
}
In javascript you need the value property to be lowercase, like this:
document.getElementById('assignedIDHiddenInput').value = s;
Then it will be set properly :) You can see an example in action here
Though if you alert the .Value it will show your value, you've actually added a new .Value property, but you haven't set the input's .value property which is what gets posted to the server. The example link above illustrates this both ways.
Also you can make it a bit faster especially if you have lots of options by using an array instead of string concatenation, like this:
var source = document.getElementById('assignedLinguistListBox');
var opts = [];
for (var i = 0; i < source.options.length; i++) {
opts.push(source.options[i].value);
}
var s = opts.join(',');
Edit: The above code is updated, CMS is right that the previous method was browser dependent, the above should now behave consistently. Also, if jQuery is an option, there are shorter ways of getting this info still, like this:
var s = $('#assignedLinguistListBox option').map(function() {
return this.value;
}).get().join(',');
$('#assignedIDHiddenInput').val(s);
You can see a working example of this here
I'm assuming ASP.NET here.
If so, your problem is the id of the control in the HTML generated by ASP.NET is not going to be "assignedIDHiddenInput" that you reference in the script. ASP.NET changes those before rendering the HTML from what you specify in the HTML page declaratively. Do a view source on the page and you will see what I mean.
Here is a way around that:
document.getElementById('<%=assignedIDHiddenInput.ClientID %>').value = s;
Update: As noted in the comments, this is only relevant if the control is set to RunAt=Server.
I think ASP.NET is calling the javascript to execute a postback on that control before your javascript function is called to populate that hidden value.
I think it's possible to disable the default postback and handle it yourself but I'm sure others can advise better.
Stick an alert() into your function there to see if it is really getting called before post-back is triggered.
I'm dynamically generating an asp form, and I would like to add the label and input elements inside a list.
For example, I would like to end up with something like:
<ul>
<li><label for="input"/><input id=input"/></li>
</ul>
To do this, I create a Label object and a TextBox object, then assign the AssociatedControlId property of the Label to link these. But I cannot add any of these in a ListItem, nor can I add these in the Controls collection of BulletedList...
Any ideas would be greatly apreciated.
The System.Web.UI.HtmlControls namespace has some useful controls.
In your aspx:
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />
In your code behind:
HtmlGenericControl list = new HtmlGenericControl("ul");
for (int i = 0; i < 10; i++)
{
HtmlGenericControl listItem = new HtmlGenericControl("li");
Label textLabel = new Label();
textLabel.Text = String.Format("Label {0}", i);
listItem.Controls.Add(textLabel);
// etc...
list.Controls.Add(listItem);
}
PlaceHolder1.Controls.Add(list);
Works like a charm.
You could probably do something like this using a Repeater.
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<label for='<%# string.Format("ctrl-{0}", Container.ItemIndex) %>'>label for ctrl #<%# Container.ItemIndex %></label>
<input id='<%# string.Format("ctrl-{0}", Container.ItemIndex) %>' type="text" />
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
If you need to add server controls to the list, you'll need to do something with the Repeater's ItemDataBound event.