Jquery select element outside of li by ID - c#

im looking to select the follow element by id toggleThisDiv. The markup looks like:
<li id="liCategory" runat="server">
<asp:HyperLink ID="lnkCategory" runat="server">
<span><asp:Literal ID="litCategory" runat="server" Visible="true" /></span>
<asp:Image ID="imgMan" runat="server" Visible="false" /></asp:HyperLink>
<asp:Button ID="btnToggleDiv" runat="server" Text="+" Visible="false" />
</li>
<div id="toggleThisDiv" runat="server" style="display:none;margin-top:-16px;">
And the jQuery:
$(document).ready(function () {
$('[id*="btnToggleDiv"]').click(function () {
$(this).next().slideToggle(100);
return false;
});
});
This works when the button is outside of the listitem but this is all inside a repeater and if i leave it like that, all of the buttons created will be next to each other instead of within their associated list item.
I'm looking for something within jQuery that would allow me to select the next div (toggleThisDiv), is this possible?
Thankyou

Use unique ID's, or classes if generating elements where the same identifier will be used.
To target an element outside the current parent of the clicked element you can find the closest parent that matches a selector, and then the next element etc.
$(document).ready(function () {
$('[class*="btnToggleDiv"]').on('click', function () {
$(this).closest('li').next('div').slideToggle(100);
return false;
});
});

Use something like this to select the toggleThisDiv
$('#<%= toggleThisDiv.ClientID %>')
When the website is generated from your asp code, your IDs will be different than what you have given them. This is because they are run at server. Anytime that you are using runat server, use the format above to find the generated ID.
You should use a class inside to repeater though.

Related

Using Select2 to make asp:dropdownlist searchable in a popup

I have a asp:DropDownList that needs to have a search bar for the user to search through the dropdown.
If I remove the line 'dropdownParent: $("#ModalPanelCard")' the dropdown displays and I can search on it, but it appears to be behind the modal. Once I reference the dropdownParent, I can't even select the dropdown - almost like it isn't calling the select2. Am I referencing the incorrect parent?
Frontend Code
<asp:Panel runat="server" ID="ModalPanelCard">
<div class="col-lg-6">
<asp:DropDownList ID="selCustomerCard" runat="server"></asp:DropDownList>
</div>
</asp:Panel>
Script
<script>
$('#<%= selCustomerCard.ClientID %>').select2({
dropdownParent: $("#ModalPanelCard")
});
</script>
Try the following:
<script>
$('#<%= selCustomerCard.ClientID %>').select2({
dropdownParent: $("#<%= ModalPanelCard.ClientID %>")
});
</script>
Just making sure the ID is right from ASP. ASP can add extra text to your HTML id, which is why we need to make sure it's the same ID.

How to call code-behind code from a unordered list item

<ul runat="server" id="ulDrop">
<li>Update?</li>
<li>
<asp:DropDownList ID="yesno" ClientIDMode="Static" runat="server">
<asp:ListItem>YES</asp:ListItem>
<asp:ListItem>NO</asp:ListItem>
</asp:DropDownList>
</li>
<li runat="server" id="liDrop" onclick="logout_Click"><span class="ondrop">Logout</span></li>
</ul>
I am trying to handle the onclick method from the LI from code-behind, so I added the following C# code:
public void logout_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Response.Redirect("log-in.aspx");
}
It keeps giving me an error, that the function cannot be found.
I am looking to clear out all session set in the asp.net page when "Logout" is clicked, not just the text but the entire LI and redirect to another page.
Please help me resolve the issue
I would prefer Marcus's answer (Adding a server control "LinkButton"). But If you would like to keep your LI and still call a server side method, as workaround you could do as follows:
Add a hidden button to your form.
<asp:button id="btnId" OnClick="logout_Click" style="display:none"></asp:button>
change your LI to
<li id="liDrop" onclick="logout();"><span class="ondrop">Logout</span></li>
Javascript
function logout()
{
document.getElementById('<%= btnId.ClientID %>').click();
}
The logout_Click method in your ASP.NET code is run on the server. The onclick attribute on the li tag refers to a JavaScript function called logout_Click that is run on the client.
In order to run the code on the server, you need to do a PostBack to the server. To test this, you can change your ASPX code as follows (this might introduce some design changes that you'd have to fix afterwards):
<li id="liDrop">
<asp:LinkButton runat="server"
OnClick="logout_Click"
Text="LogOut" />
</li>
This adds a LinkButton control that posts back to the server so that the logout_Click method is run.
The li element - even with runat="server" - is still a HTML element. When you use the onclick-Attribute of that element, it will treat it as a call to a client side JavaScript-function (which isn't defined).
The code behind is server side and cannot be executed from HTML elements. You need ASP Elements for that to work.

The server tag is not well formed.(databinder.eval)

I am trying to working the following code.
<asp:DataGrid ID="Grid" runat="server" DataKeyField="KeyID" CssClass="grid"
...
<asp:CheckBox runat="server" ID="checkBox-<%#DataBinder.Eval(Container.DataItem,"KeyID")%>" AutoPostBack="false"></asp:CheckBox>
When I run the code,I have got the below error:
Error 25 The server tag is not well formed.
Note : This is working without runat="server".
What is the remedy for this problem ?
You don't need to set the ID of the CheckBox to do what you want to do (change the background color). Your CheckBox should look like this (I added the KeyID as the text value if you want to display it... or you can just remove that if you only want the checkbox):
<asp:CheckBox runat="server" ID="checkbox" Text='<%# Eval("KeyID") %>' AutoPostBack="false"></asp:CheckBox>
Now your checkbox will render something like this:
<input id="MainContent_Grid_checkbox_0" type="checkbox" name="ctl00$MainContent$Grid$ctl02$checkbox" /><label for="MainContent_Grid_checkbox_0">Value of KeyID</label>
Since all the names end with "checkbox", you can apply a function on the change event for those elements whose name ends with "checkbox". You didn't specify that this was a JavaScript question or if you are using jQuery... this answer uses jQuery:
<script>
$('input[name$="checkbox"]').change(function () {
if ($(this).is(':checked')) {
$(this).parent().css('background-color', 'yellow');
}
else {
$(this).parent().css('background-color', 'white');
}
});
</script>
That will determine if the checkbox is checked, and if so it will set the background-color of its parent (the <td> that it is in, inside the DataGrid rendered HTML), depending on the value.
Likewise, you can go up to the next parent() and highlight the entire row.
Resources:
jQuery Selectors
OnCheckedChanged -- an event that you would process in the code behind, not in JavaScript.

Triggering a postback from Javascript fails

I am trying to trigger a postback if a certain condition is true. Initially, a user will click on a button on my form, the server does some work, and in the process of doing that work it assigns a hidden field the value of '1'. When the page reloads after that very first postback, I am trying to use javascript to check the hidden field, and if it is '1' I need the page to postback again so the server side can do some additional processing. The reason for doing it this roundabout way is so that I can create controls on the form from my C# code behind as well as download a file in 1 user interaction. Here is what I have so far:
<script type="text/javascript" language="JavaScript">
function atload() {
var HWInfo = document.getElementById('HiddenHW').value;
if (HWInfo == '1') {
alert("flag has been set");
__doPostBack('<%= hdnHidden.UniqueID %>', '');
}
}
$(document).ready(atload);
</script>
The alert that says the flag has been set correctly fires, but the __doPostBack does not. In my ASPX file, here is the relevant part:
<form id="InventoryForm" runat="server">
<div>
<asp:Label ID="lblClientList" runat="server" Text="Client List"></asp:Label>
<asp:DropDownList ID="comboClientList" runat="server"></asp:DropDownList>
<asp:Label ID="spacer1" runat="server" Text=" "></asp:Label>
<asp:Button ID="btnGenerateHWReport" runat="server" Text="Generate Hardware Inventory Report" />
<asp:Label ID="spacer2" runat="server" Text=" "></asp:Label>
<asp:Button ID="btnGenerateSWReport" runat="server" Text="Generate Software Inventory Report" />
<br />
<br />
<asp:Panel ID="MissingCompPanel" runat="server"></asp:Panel>
<asp:HiddenField ID="HiddenHW" runat="server" Value="0" />
<asp:HiddenField ID="hdnHidden" runat="server" />
</div>
</form>
I can tell the postback never fires, because I have breakpoints in the Page_Load C# codebehind that never get tripped. I have break points on almost every single line of this:
if (!Page.IsPostBack)
{
// Page is not a postback, this is the first visit here
string foo = HiddenHW.Value;
}
else
{
// Page is a postback and not initial load
string foo = HiddenHW.Value;
}
Why is my __doPostBak after the alert not firing, and is there a better way to do this? The end result I want is if my hidden field is '1', then I want my 2nd trip to the server to 1) actually happen and 2) know that the hidden field is '1' and not its default '0'.
Thanks!
how about just clicking the submit button programatically and have it call __doPostBack the way it normally does?
Try invoking the __doPostBack method on the page instead of the hidden control
__doPostBack('__Page', '');
When you get the value of HiddenHW, you're not using the right ID. If you look at the rendered source, the ID of the control is something like ctl00_HiddenHW. To get that ID, you should use HiddenHW.ClientID. I believe __doPostBack also needs the ClientID, not UniqueID.
function atload() {
var HWInfo = document.getElementById('<%= HiddenHW.ClientID %>').value;
if (HWInfo == '1') {
alert("flag has been set");
__doPostBack('<%= hdnHidden.ClientID %>', '');
}
}

Find the ID after compiling

When you assign something an ID in asp.net such as:
<asp:Label runat="server" ID="mylabel" Text="some text"></asp:Label>
The code behind ID you use to reference that object is mylabel.
However after the site has compiled and is running the ID in the HTML changes to something a bit more abscure
<asp:Label runat="server" ID="ct100_blahblah_what_mylabel" Text="some text"></asp:Label>
And I cannot (don't know how) to reliably predict what it will be to select it with javascript.
Is there a way to ask the server what the ID for that label is at any given moment?
What are some keywords could use to find out more about this phenomenon?
You need the ClientID property. This contains the generated id of the control at runtime. You could emit some JavaScript in the code behind that sets the client id of your control to a JavaScript variable so you can reference it.
EDIT: added example
The following will find the label using the ClientID and then update its text.
<html>
<body>
<asp:Label runat="server" ID="mylabel" Text="some text"></asp:Label>
<script language="javascript">
var mylabelID = "<%= mylabel.ClientID %>";
var label = document.getElementById(mylabelID);
label.innerHTML += " changed";
</script>
</body>
</html>
I believe you are looking for the ClientID property.
The ClientID value is often used to
programmatically access the HTML
element rendered for a control in
client-side script.
Your other option is to wrap your control in an HTML element like this:
<span id="foo">
<asp:Label runat="server" ID="mylabel" Text="some text"></asp:Label>
</span>
Since this outer element does not have the runat="server" attribute, its id will not be changed on render. This would mean that your JavaScript function would have to to be changed to pull an inner element from the span foo or if you are using a JavaScript framework like jQuery you could pull the label back like this:
$("span#foo span");

Categories