I have a UserControl (with FileUpload) included on a Master Page as follows:
Master Page
<uc:uploadFiles ID="UC1" runat="server"/>
uploadFiles.ascx
<script type="text/javascript">
function ValidateUpload() {
var FileUpload_function = document.getElementById('myfile');
if (FileUpload_function.value == '') {
return false;
}
else {
//do stuff }
return true;
}
</script>
<div id="div_FileUpload" class="FileUpload_content" runat="server">
<asp:FileUpload ID="myfile" class="FileUpload" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="myfile" ClientValidationFunction="ValidateUpload" />
</div>
When I run the page I get the following error caused by the CustomValidator:
Unable to get property 'value' of undefined or null reference.
My guess is that the FileUpload value is validated before the entire page is rendered because when I delete the UserControl and move the codes to the MasterPage directly, the CustomValidator works fine.
How can I solve the problem?
You need to use .ClientID in document.getElementById. Becasue when you use that in user control, cotnrol id - myfile might be renamed to something else, like ct00_myfile and in that case if you execute same js code, it will give you null.
You need to use following js code.
var FileUpload_function = document.getElementById('<%=myfile.ClientID %>');
Related
I am trying to invoke a server side method through JavaScript by first displaying a confirm message and then trigger a button click on the page to call the function. However, the .click() method doesn't seem to work. Any ideas?
<script type="text/javascript">
function confirmDelete() {
var button = document.getElementById("hiddenButton");
if (confirm("Are you sure you would like to delete the row")) {
button.click();
}
}
</script>
and the button is defined like follows
<asp:Button ID="hiddenButton" runat="server" onclick="showHiddenMessage" Text="hidden" width="100px" />
Everything that I have found suggest that it should. including here:
http://www.comptechdoc.org/independent/web/cgi/javamanual/javabutton.html
and here:
Call ASP.NET function from JavaScript?
var button = document.getElementById('<% =hiddenButton.ClientID %>');
Id of server side controls is different on client side. modify code as above and try.
Modify confirmDelete() method as below:
function confirmDelete() {
if (confirm("Are you sure you would like to delete the row")) {
__doPostBack(( 'hiddenButton', '' );
}
}
Take a look at the ClientIDMode property of a Button. Setting this to Static will cause the button to render with the ID you entered in to your ASP.NET code. https://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx
<asp:Button ID="hiddenButton" runat="server" ClientIDMode="Static" onclick="showHiddenMessage" Text="hidden" width="100px" />
If you look at the generated HTML, you should see the ID of this button as hiddenButton which should allow your Javascript to work.
By default ClientIDMode value will be Inherit, and will include the NamingContainer within the ID. This means the ID of the rendered HTML will be something like Panel1_hiddenButton and your Javascript won't find it with the current code.
For reference:
Static - The ClientID value is set to the value of the ID property. If the control is a naming container, the control is used as the top of the hierarchy of naming containers for any controls that it contains.
Inherit - The control inherits the ClientIDMode setting of its NamingContainer control.
But why don't you use your javascript function with your button? I think it is better:
<script type="text/javascript">
function confirmDelete() {
if (confirm("Are you sure you would like to delete the row?")) {
return true;
}
return false;
}
And your button:
<asp:Button ID="hiddenButton" runat="server" OnClientClick="return confirmDelete();" onclick="showHiddenMessage" Text="hidden" width="100px" />
In this case if user will click OK button, your showHiddenMessage function will occur. Otherwise nothing will be happen.
All,
Environment: ASP.NET 2.0, AjaxToolkit build 1.0.20229.0, IE9
I am using $find() to find a behaviour of a call out extender so I can show explicitly using .show() method. Unfortunately, $find() returns null.
$find('my auto generated behvaiour Id').show();
FYI: The BehaviorID on the ValidatorCalloutExtender is generated using ClientID of the control (ClientID_ + "BehaviourID" <- is also what I use in my $find() function) because I have many instances of this control on the same page.
I looked at the rendered code and I can see JS to create that creates the behaviour:
Sys.Application.add_init(function() {
$create(AjaxControlToolkit.ValidatorCalloutBehavior ...
The $find() executes AFTER a postback in an UpdatePanel and returns always null.
EDIT (ADDED):
I created new page and below is the code, find() returns still null,- is there a bug in Ajax control tooklit for ASP.NET 2.0?
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScripManager1" runat="server" EnablePageMethods="True" >
</asp:ScriptManager>
<asp:TextBox runat="server" ID="txtInputField" />
<asp:RequiredFieldValidator runat="server" ID="valInput"
ControlToValidate="txtInputField"
ErrorMessage="ERROR STRING"
Display="none" /> <ajaxToolkit:ValidatorCalloutExtender runat="server" ID="extValInput" TargetControlID="valInput" BehaviorID="myID" />
<asp:Button runat="server" ID="btn" OnClick="btn_click" CausesValidation="True" />
<script type="text/javascript">
var obj = $find("myID");
alert(obj);
</script>
</form>
ADDED:
After observation in JS debugger, I realized that the validator callout extender only appears (is added dynamically to the DOM) when there's error, hence, if there's no error you cannot find it.
THE QUESTION NOW IS: How to reposition the call out extender baloon before displaying it? It is really catch 22, you can't access it when it is not displayed and when it is displayed, it is already to late because it displays in the wrong place.
The cause of the problem is that you try to find component before page completes component initialization. Try to access your editor in Sys.Application.add_load event handler. I tried the following code and everything works fine:
<script type="text/javascript">
Sys.Application.add_load(function() {
var obj = $find("myID");
alert(obj);
});
</script>
Edit:
To address your latest question: how you can reposition it. Callout ValidatorCalloutExtender uses PopupExtender to show it. So, you can try to bind to 'showing' and 'shown' events of the popup extender and then try to reposition callout.
<script type="text/javascript">
Sys.Application.add_load(function() {
var callouotComponent = $find("myID");
var popupBehavior = callouotComponent._popupBehavior;
popupBehavior.add_showing(function(){alert("I am showing");});
popupBehavior.add_shown(function(){alert("I was shown");});
});
</script>
Note: I didn't verify this code, but it can be used as start point.
Modified your code and verified, popup position is changing.
<script type="text/javascript">
Sys.Application.add_load(function () {
var callouotComponent = $find("myID");
//Below line is to init popup ballon, otherwise popup behaviour will return null
callouotComponent._ensureCallout();
var popupBehavior = callouotComponent._popupBehavior;
popupBehavior.set_x(100);
popupBehavior.set_y(100);
});
</script>
I created web page in that i used javascript in .aspx file.
I have a save-button,but in the source code i used javascript for save button, where i declared a function called OnClientClick="javascript : validateTextTest()" and in the head of source code i called this function validateTextTest().
Below is the save button in source code:
<asp:Button ID="Save" runat="server"
onclick="Save_Click" Text="Save"
OnClientClick="javascript : validateTextTest()" Width="63px" />
Now i need to call a function validateTextTest() in save button of .cs file.Because i have two to three textboxs, if i leave one texbox out of three textbox it should not insert into DB.
So please tell me how to call the function in .cs file.
Insted of doing such things , you can use asp.net validation controls , for your purpose you are going to need a RequieredFieldValidator for each one of your TextBoxes , and you can use them like following code :
<asp:TextBox ID="txtISBN" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RQVISBN" runat="server" ErrorMessage="*" ControlToValidate="txtISBN"></asp:RequiredFieldValidator>
These controls are greate ! And they do validation on clientSide as you want ;)
validateTextTest is your javascript function which you probably use for some client side validations before submitting to the server. So i dont think you really should use the client side function in your sever side code (.cs file) to validate the input. You should do the same validation inside your server side code also. Something like this
if((!String.IsNullOrEmpty(TextBox1.Text)) &&
(!String.IsNullOrEmpty(TextBox1.Text)) &&
(!String.IsNullOrEmpty(TextBox1.Text)))
{
// Insert to DB
}
else
{
//Show validation error message
}
You need to firstly start off by defining the technology stack you are using. Is it ASP.NET or MVC.
I am assuming you are using ASP.NET. Given the way you have already started writing this application. You will need to do a few things to get your approach to work.
<form name="myform">
<asp:HiddenField runat="server" id="validRequest"/>
<script type="text/javascript">
function validateTextTest() {
//validation goes here
var validRequest = document.getElementById(<%#validRequest.ClientID%>);
//set validation outcome to the validRequest etc
validRequest.value = 'true';
if(validRequest.value == 'true')
return true;
return false;
} </script>
</form>
I forget which one it is but check either your Page_Load etc
protected void Page_Load(object sender, EventArgs e)
{
if(validRequest.Value == "true")
//Do whatever you need to
}
I have a aspx page (default.aspx), inside which I am loading a user control (tree.ascx).
inside the tree.ascx there is a hidden field.
<asp:HiddenField ID="HiddenField1" runat="server"/>
I am assigning a value to the hidden field using javascript.
document.getElementById('<%=HiddenField1.ClientID%>').value = "some text here";
alert(document.getElementById('<%=HiddenField1.ClientID%>').value);
document.getElementById('form1').submit();
The alert displays the value absolutely fine. which means the value gets inserted in the hidden field properly.
But when I am posting back to server and checking the value, it is always null.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// do something.
}
else
{
string str = this.HiddenField1.Value;
}
}
My code is always getting a empty string here. somehow the postback is erasing the value from the hidden field.
What could be the reason?
Try using below syntax. It works for me even after postback.
ASPX code
<asp:HiddenField runat="server" ID="aspHiddenField" />
<input type="hidden" id="inputHidden" value='<%= aspHiddenField.ClientID %>' />
JavaScript Code
var inputHidden = document.getElementById('inputHidden');
$("#" + inputHidden.value).val("some text");
Code Behind
if (!string.IsNullOrEmpty(aspHiddenField.Value))
{
//Your code goes here
}
Check if your control is within a master page, if it is, then you need to access it like that, 1st Master Page->within master page look for the control's value, it will work surely.
Place your hidden field in update panel like :
<asp:UpdatePanel ID="UpnlHidden" runat="server">
<ContentTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
This will work for you :-)
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" />