Setting a panel to visible using javascript - javascript

How can I make a <asp:Panel> visible using javascript?
I have done the following but get an error (Cannot Read property style of null)
<asp:Panel runat="server" id="panNonAfricanCountries" Visible="false">
var panNonAfricaDropDown = document.getElementById("panNonAfricanCountries")
if (dropDownFirst == "Yes") {
panNonAfricaDropDown.style.visibility = "visible";
}

The Visible="false" on an asp.net control have as result to not render the control on the page.
What you try to do here is to render it, but with css style to have it hidden from the user until using javascript show it. To archive that do not use the Visible, but set a style or a css to your Panel.
<asp:Panel ID="PanelId" runat="server" Visible="true" style="visibility:hidden" >
Some Content here...
</asp:Panel>
The asp.Panel is render as div and your html on the page will probably as:
<div id="PanelId" style="visibility:hidden">
Some Content here...
</div>
and I say probably because we do not know for sure how the Id is rendered. To get it we use the PanelId.ClientID and your final javascript code will be:
var panNonAfricaDropDown = document.getElementById("<%=PanelId.ClientID%>");
if (dropDownFirst == "Yes" && panNonAfricaDropDown) {
panNonAfricaDropDown.style.visibility = "visible";
}

ASP.NET mangles the names of elements that run on the server. You will have to find the mangled name and then do document.getElementById on that name.
Alternatively, you can use the ClientIDMode property of asp:panel to turn off the mangling (http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx)

Related

Checking Div Visibility in ASP.NET using Javascript

How do you check if a div's visibility is hidden using JavaScript and ASP.Net?
If you look below, I am using an "if statement" to return an Alert("hi") if the div is not visible. Yet, the code is not working.
Any help is appreciated, thank you. Language is C#/JavaScript
<script>
function emptyRunReportConfirmation() {
var divDateFiltersID = document.getElementById('<%=divDateFilters.ClientID%>');
if (divDateFiltersID.style.visibility == "hidden") {
alert("hi");
}
}
</script>
<!-- this is a button to call the function -->
<asp:Button ID="buttCustomerFilt" runat="server" class="btn btn-primary" ClientIDMode="Static" Text="Run Report" OnClientClick="if ( ! emptyRunReportConfirmation()) return false;" OnClick="buttCustomerFilt_Click" /></div>
<!-- this is the div to check if visible -->
<div runat="server" id="divDateFilters" visible="false"></div>
Setting visible="false" on a runat="server" element will remove the element entirely from the page. The DIV element will not render at all. You could check your HTML to verify this.
It depends a bit on what you want to do, but in this case if you use visible="false" you can check if the variable is empty to see if the element exists.
if (!divDateFiltersID) {
alert("hi");
}

Javascript-error on finding object

im stuck with Javascript in Asp.net...
I made a TextBox named tbValidFrom and another named tbValidTo.
I also made two ModalPopups.
Then i try to open the ModalPopupExtenders when the TextBoxes get focus:
<script type="text/javascript">
$('#tbValidTo').focus(function () {
$find('ModalPopupExtenderNV1').show();
})
$('#tbValidFrom').focus(function () {
$find('ModalPopupExtenderNV2').show();
})
</script>
but it doesnt finds tbValidTo or ModalPopUpExtender ?
Runtime-Error in Microsoft JScript: Object expected
Here is one of the two ModalPopupExtenders and TextBoxes:
<asp:TextBox ID="tbValidFrom" runat="server"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanelNV2" runat="server" RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<cc1:ModalPopupExtender ID="ModalPopupExtenderNV2" runat="server" TargetControlID="HiddenField6"
PopupControlID="PanelNewVersion" BackgroundCssClass="modalBackground" BehaviorID="ModalPopupExtenderNV2"
Enabled="True" />
<asp:HiddenField ID="HiddenField6" runat="server" />
</ContentTemplate
</asp:UpdatePanel>
The same as above is with the other ModalPopupExtender and TextBox...
Help would be really nice.
Thanks
Edit: Yes i use a masterpage!
Fails where it is marked yellow.
your jQuery syntax is wrong.
change your script to:
<script type="text/javascript">
$('#tbValidTo').focus(function () {
$(this).find('#<%=ModalPopupExtenderNV1.ClientID%>').show();
});
$('#tbValidFrom').focus(function () {
$(this).find('#<%=ModalPopupExtenderNV2.ClientID%>').show();
})
</script>
elements that has runat="server" will eventually end with a different ID than you entered in the aspx file.
i used the <%= %> to get the 'final' id.
hope that helps
Seeing that markup there is two chances for the issues.
With the ModalPopupExtender.
Where you have given the panel "PanelNewVersion" . Seems like its missing in the markup.
In the Javascript code. If you want to hide that Popup, give the name of the panel. NOt the name of the ModalPopupextender.
Also you have given an update panel there in page, so you can easily handle the modalpopup in any srever side event of your textbox.
Otherwise, if you want to use the Modal popup ijn client side, use jQuery Modalpopup. That will the better option.
ASP.NET Can modify the ID's of elements, if you use a Masterpage the element id's will be modified to something like the following : ctl001_ContentPlaceHolder1_tbValidFrom
To get around this ASP.NET modification of your elements you can use ASP.NET Inline Expressions to get the rendered ID from the object.
See the answer to the following question for more information on ASP.NET Inline Expressions
You can look at changing the Client ID Mode (The way ASP.NET Modifies IDs when the page is rendered) here :
ASP.NET Client ID Modes
EDIT :
The AjaxControlToolkit's ModalPopupExtender is not rendered on the page as a html element, therefore you cannot find this item using the ClientID of the ModalPopupExtender.
You must use the BehaviourID to call the show function on.
The below code should work correctly :
$('#<%= tbValidTo.ClientID %>').focus(function () {
$find('ModalPopupExtenderNV1').show();
})
$('#<%= tbValidFrom.ClientID %>').focus(function () {
$find('ModalPopupExtenderNV2').show();
});
This will find the textbox object using the ASP.NET Inline expressions to find the client ID and will then find the behaviour ID and execute the Show method.
Example Markup :
<script type="text/javascript">
$(document).ready(function() {
$('#<%= tbValidFrom.ClientID %>').focus(function () {
$find('ModalPopupExtenderNV2').show();
});
});
</script>
<asp:TextBox ID="tbValidFrom" runat="server"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanelNV2" runat="server" RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<cc1:modalpopupextender id="ModalPopupExtenderNV2" runat="server" targetcontrolid="HiddenField6"
popupcontrolid="PanelNewVersion" backgroundcssclass="modalBackground" behaviorid="ModalPopupExtenderNV2"
enabled="True" />
<asp:HiddenField ID="HiddenField6" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="PanelNewVersion" runat="server">
testing panel
</asp:Panel>

Hiddenfield in a usercontrol, can not access it on clientside

I have a hidden field in a User Control. At run time I assign the hidden fields ClientId to an anchor tag like this:
aClickSort1.HRef = string.Format("javascript:SortImage({0},{1});", divArrowUp1.ClientID, hiddenSort1.ClientID);
The thing is that when I try to get the hidden fields ClientId in client side code, it is undefined.
How can access it on the client side code?
Ps. The HiddenField is in a usercontrol
Regards Örvar
When you set Visible="false" to server side control, it will not be sent at all to the client.
Instead, set style="display: none;" or even better via CSS then it will be sent to the browser and still be hidden.
It seems that the reason is the non-visible container. If you have something like:
<asp:panel id="panel1" runat="server" Visible="false">
<asp:hiddenfield id="hiddenfield1 runat="server" value="123"/>
</asp:panel>
You cannot access the stuff in panel1 as things are not rendered for server side controls with visible="false" attribute.
You can set it into a div with style="display:none;" or just leave hiddenfield outside the non-visible container as it is not visible anyway.
You need to set hiddenSort1's ClientIdMode to Static.
Like this:
<asp:HiddenField ID="hiddenSort1" runat="server" ClientIDMode="Static" />
From javascript:
var hiddenSort1 = document.getElementById('hiddenSort1');
Correct me if I am wrong, but isn´t the Id generated and if you have the hidden field in a user control it will get the Id of:
myUserControlName$myHiddenFieldId
?

Creating a Button Click Event and Validating TextBoxes using Javascript

I am having so much trouble with this. I have looked everywhere so I hope someone can either explain to me how to do this or show me. Here's my problem:
I have a DataGrid filled with DataBound Items (ItemTemplate) which was created using ASP.Net.
My reason for the ItemTemplates over a regular DataBound field is to enable the Edit Mode of the DataGrid. In my ItemTemplates, I have labels to display the data and two option buttons (Edit/Delete). I've got the buttons working in the code behind (C#).
Edit places the DataGrid in Edit Mode. In the EditItemTemplates I've got DropDownLists, TextBoxes, and a Save button in place of the Edit button.
The Save button also works with the code I've written for it. All-in-all, the DataGrid works beautifully and displays everything neatly. However, there is one final job I want the Save button to do: I want it to check the TextBoxes and validate that the values entered match the criteria I have set (keep in mind that these are in EditItemTemplates).
I have Javascript already written that will check for validation. I want a modal window (that I have already set up) to display and I want the CSS of the TextBoxes in question to change.
I want to do this using Javascript but my problem is that I can't check for the Save button to create the Click event and I can't 'locate' the TextBoxes to validate them. Is there a way I can 'find' those elements while the DataGrid is in Edit Mode?
Here's a small bit of the code used to create the DataGrid if it helps:
<asp:DataGrid ID="dgCamsizer" CssClass="data" runat="server" AutoGenerateColumns="False"
GridLines="None" OnItemCommand="dgCamsizer_ItemCommand" ShowHeader="true">
<Columns>
<asp:TemplateColumn HeaderStyle-CssClass="infoHeaderDG">
<HeaderTemplate>
Operator</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Operator" Text='<%# DataBinder.Eval(Container.DataItem, "Operator") %>'
runat="server" /></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="EditOper" Width="40px" Text='<%# DataBinder.Eval(Container.DataItem, "Operator") %>'
runat="server"></asp:TextBox></EditItemTemplate>
<HeaderStyle CssClass="infoHeaderDG"></HeaderStyle>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderStyle-CssClass="infoHeaderDG">
<ItemTemplate>
<asp:Button ID="Edit" Text="Edit" CommandName="Edit" runat="server" /></ItemTemplate>
<EditItemTemplate>
<asp:Button ID="Save" Text="Save" CommandName="Save" runat="server" /></EditItemTemplate>
<HeaderStyle CssClass="infoHeaderDG"></HeaderStyle>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Perhaps I should re-phase my question: I managed to 'find' the TextBoxes thanks to Zetlen. I've also managed to get the values. Now... How do I use those values to test for validation?
Here is the code I used to get the values:
$("#<%=dgCamsizer.ClientID %> :text").each(function () {
alert($(this).val());
});
ASP.NET webforms are hard to work with in JavaScript, because the IDs of your HTML elements change during the page lifecycle! The input you're calling "EditOper" will get an HTML ID of something like "dgCamSizer_ctl102_EditOper". One thing you can do is collect these elements on pageload in a cache of DOM element references. I recommend using jQuery or a similar DOM querying library.
<script type="text/javascript">
$(document).ready(function() {
var $editorElms = {},
idSeparator = "_"; // the underscore is ASP.NET's default ID separator, but this can be changed if you wish with the IDSeparator property.
$('#dgCamSizer input').each(function() {
$editorElms[this.id.split('_').pop()] = $(this);
});
// now you can access every input using the $editorElms hash.
// e.g.
function someValidationRoutine() {
if (!$editorElms.EditOper.val()) {
someErrorDisplayer("EditOper must not be blank.");
return false;
}
}
})
</script>
And, again using jQuery, the Save button shouldn't be too tough to find.
var $saveButton = $('#dgCamSizer :submit[value=Save]');
So you can bind the event that way:
$saveButton.click(function(e) {
if (!someValidationRoutine()) {
e.preventDefault();
}
});
This is not the most high-performance solution--selectors of that complexity are always a bit slower. But it gets the job done without messing too much with the DataGrid.
So I managed to solve my own problems and answer my own question. I was able to get the id's of all of the TextBoxes and I even placed them into an array to be used for my validations. Here's what I used to do all of this:
var i = 0;
var data = [];
$("#<%=dgCamsizer.ClientID %> :text").each(function () {
data[i] = $(this).attr("id");
i++;
});

getElementById not finding control generated by ASP.net

I am simply trying to store a label in a variable in javascript but for some reason this isn't working with document.getElementById('control');. I know my javascript is linking to my html file fine because everything else works.
Here is my javascript code:
function performEvapCooledCircuit(txt)
{
var error = document.getElementById('lblError');
if (txt.value == null || isNaN(txt.value))
{
error.style.visibility = "visible";
}
}
Here is the html code for my label:
<asp:Label ID="lblError" class="NormLabel" runat="server"
style="color:red; visibility:hidden;" Text="Invalid Input."></asp:Label>
I am getting an error that says object expected??
The ID that ASP.NET will generate will not be "lblError" so you'll need to reference it by its ClientID
document.getElementById('<%=lblError.ClientID %>');
If your javascript file is external I've usually had to write a type of "Init" javascript method to make sure my ID's were set up property
On your ASPX page:
<script type="text/javascript">
var lblError = null;
function InitializeVariables()
{
if (lblError == null) // make sure you only do this once
{
lblError = document.getElementById("<%=lblError.ClientID %>");
}
}
</script>
<asp:Label
ID="lblError"
class="NormLabel"
runat="server"
style="color:red; visibility:hidden;"
Text="Invalid Input."></asp:Label>
Then in your javascript file you'll have to call InitializeVariables() to make sure you've got the variables pointing to the proper asp.net controls
function performEvapCooledCircuit(txt)
{
InitializeVariables();
if (txt.value == null || isNaN(txt.value))
{
lblError.style.visibility = "visible";
}
}
"hunter" gives a pretty solid way of doing things, however a, in my opinion far better method is to use the "CliendIDMode" property on the control and set that property to "Static". This will make the client and server IDs the same. Like this:
<asp:TextBox ID="ServerAndClientId" runat="server" ClientIDMode="Static" />
The ID of the label is not "lblError". The ASP.net engine changed the ID. Check the HTML source code in the browser to find out the real ID.
That's not HTML for the label, that is an ASP.NET Control which will be rendered into HTML before it is sent in the response. ASP.NET WebForms controls sometimes change the id for the HTML they create.
View the source of the webpage to see what the id for the HTML element is on the rendered page.
You can use this:
document.getElementById('<%= lblError.ClientID %>').click()
Starting from ASP.NET 4.0 you can use ClientIDMode property for you element. And if you set it into Static then the ClientID value will be set to the value of the ID property:
<asp:Label ID="lblError" runat="server" ClientIDMode="Static" />
will be rendered as something like this:
<span id="lblError" name="ctl00$MasterPageBody$ctl00$Label1" />

Categories