ASP Textbox default invisible and visible from JS - javascript

I have a textbox which will be initally invisible and checkbox OnClick JS method , I want the button to be visible ,
initally the checkbox seems invisible but when i click on the checkbox, JS Method gives me the error with object not found. and if i remove the Visible="false" from textbox code works fine.
<asp:Textbox id="day" runat="server" Visible="false" />
<asp:CheckBox ID="parts" runat="server" onClick="Click();" />
<script type="text/javascript">
function Click(){
document.getElementById("day").style.visibility = "visible";
//ERROR **0x800a01a8 - Microsoft JScript runtime error: Object required**
}
</script>
//ERROR 0x800a01a8 - Microsoft JScript runtime error: Object required

When you use visible=false, that is never rendered on page, implies, you can not do document.getEle.., it will always give you null value and hence , it will throw error.
If this property is false, the server control is not rendered. - MSDN
How to solve this
So it make it work, you need to make it hidden using javascript and then make it visible using javascript.
<asp:TextBox ID="day" runat="server" style="display:none;" />
<asp:CheckBox ID="parts" runat="server" onClick="Click();" />
<script type="text/javascript">
function Click() {
document.getElementById("day").style.display = "block"; // use "none" to hide
}
</script>

Use the static id mode instead, to stop it using an auto-generated id:
e.g.
<asp:Textbox id="day" ClientIDMode="Static" runat="server" Visible="false" />
Also as you tagged this as jQuery the simpler jQuery could would look like this (if the code follows the elements on the page):
$('#day').click(function(){
$(this).show();
});
or this if the code precedes the elements, wrap it in a DOM ready handler:
$(function(){
$('#day').click(function(){
$(this).show();
});
});
$(function(){...}); is just a handy shortcut for $(document).ready(function(){...});

Related

how to disable button after first click in javascript

I am new to C#. I have a save button inside InsertItemTemplate. I have used the following code to disable the button after first click in java script but its not even working for the first click please help me.
<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Add" CausesValidation="true" OnClientClick="this.disabled='true';return true;" />
You are modifying the "disabled" property of the DOM object on the browser, but the button will do a post back to the server when it's clicked, so any change to the DOM will be lost.
On the function where you handle the command "Add" in your server code you must retrieve the button from the InsertItemTemplate and set its "Enabled" property to false, that will disable the control from the server side.
If you want to avoid multiple clicks while the page has not been reloaded then you need a client function to avoid this, something like this:
<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Add" CausesValidation="true" OnClientClick="return checkEnabled(this);" />
<!-- somewhere in your page -->
<script>
function checkEnabled(item)
{
if(item.disabled != 'true')
{
item.disabled = 'true';
return true;
}
return false;
}
</script>

Control is not declared. It may be inaccessible due to its protection level

I'm really stuck and I've tried all the other examples but nothing works. I'm fairly new to ASP.NET but learning fast!
I want to use the jQuery datepicker and I am inserting this script
<script>
$(document).ready(function () {
$(function () {
$("#" + '<%=txtDOB.ClientID%>').datepicker();
});
});
</script>
and my control on the aspx page is
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server"></asp:TextBox>
As soon as I close the the server tag %> the red line appears under the txtDOB control and says:
txtDOB is not declared. It may be inaccessible due to its protection level.
I've made the class public in the code behind but doesn't make any difference. I've also moved the script to the bottom of the page. If I change the asp textbox to a HTML input it works fine.
It will work fine with an ASP.NET TextBox as you have used. Therefore it must be to do with where your control is located. For example, if it's inside a Repeater or Grid, you will not be able to use its ID directly like that, since the framework will generate unique ids for each row at runtime.
Create a simple webform with no other controls on the page, and you will find it works just as you have it.
Try using static ID mode instead:
<script>
$(document).ready(function () {
$("#txtDOB").datepicker();
});
</script>
It makes the client script easier (especially when you move it to an external .js file to take advantage of caching), and is an easy change to the ASP control:
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server" ClientIDMode="Static"/>
You could use a different type of jQuery selector to select for that ID as follows:
<script>
$(document).ready(function () {
$("input[id$=_txtDOB]").datepicker();
});
</script>
That selector will account for the text that is being appended to the beginning of your ID due to the use of your CreateUserWizard control. It is cleaner than the way you are currently doing it, and you can use your original HTML.
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server"></asp:TextBox>

vb .net, javascript issue involving strict mode

I have a VB .net application that I am attempting to integrate with a former deverlopers code.
The code takes a zipcode and returns a list of stores, along with their location on a google map canvas.
The process works great, with one exception.
I get the following error
JavaScript runtime error: Accessing the 'caller' property of a
function or arguments object is not allowed in strict mode.
I have isolated the culprit to
__doPostBack('userControlSearchResults_results', LatLng);
Which internally has the following
function Sys$WebForms$PageRequestManager$_doPostBack(eventTarget, eventArgument) {
var event = window.event;
if (!event) {
var caller = arguments.callee ? arguments.callee.caller : null;
if (caller) {
var recursionLimit = 30;
while (caller.arguments.callee.caller && --recursionLimit) {
caller = caller.arguments.callee.caller; // ERRORS HERE
}
event = (recursionLimit && caller.arguments.length) ? caller.arguments[0] : null;
}
}
...
My first inclination was to create a window.event so it by passes the if(!event) and moves on.
Since, there are other times we call __doPostback in the code and it is successful.
However since my JavaScript is limited, i am either doing it wrong or need to find a different approach.
I have searched for this problem and very little has come back. The common response is to just comment out the 'use strict'; and move on.
The problem is we pull in a lot of JavaScript libraries and many of them are now set to 'use strict'
Does anyone have a suggestion or an idea on how to address this?
A blog made reference to trying to apply a setTimeout() before the __doPostback call.
However I do not see how that would resolve anything.
Edit: Added some more code.
__doPostback is within the following javascript
function CompleteSearch(returnedLatLng) {
if (returnedLatLng != '') {
alert("dopostback here2- this is where it breaks");
__doPostBack('ucSearchResults_udpResults', returnedLatLng);
if (document.getElementById("sidebar_search")) { document.getElementById("sidebar_search").style.display = "none" };
if (document.getElementById("sidebar_login")) { document.getElementById("sidebar_login").style.display = "none" };
if (document.getElementById("promo1")) { document.getElementById("promo1").style.display = "none" };
document.getElementById("sidebar_results").style.display = "block";
//document.getElementById("sidebar_results").style.display = "none";
}
return false;
}
Where as my update panel is within a user control and looks like this...
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div id="Container" style="zoom:1" onclick="">
<asp:UpdatePanel runat="server" ID="udpResults" OnLoad="UpdatePanel1_Load">
<ContentTemplate>
<asp:HiddenField ID="currentLatLong" runat="server" />
<asp:HiddenField ID="triggerSearch" runat="server" Value="0" />
<asp:HiddenField ID="searchString" runat="server" Value="0" />
<asp:HiddenField ID="locationCode" runat="server" />
<asp:HiddenField ID="locationDesc" runat="server" />
<asp:HiddenField ID="locationPhone" runat="server" />
<asp:HiddenField ID="locationZip" runat="server" />
<asp:HiddenField ID="filterPickup" runat="server" />
<asp:HiddenField ID="filterVirtualKiosk" runat="server" />
<asp:HiddenField ID="filterDelivery" runat="server" />
<asp:HiddenField ID="filterAcceptsCash" runat="server" />
<asp:HiddenField ID="filterKey2Key" runat="server" />
<asp:HiddenField ID="filterHODService" runat="server" />
<asp:Label ID="tblResults" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Does this help or would more code be required.
I am really stuck right now and do not know where to proceed.
This problem occurs when window.event contains null.
I found that it contains null on a JavaScript timer event only.
Maybe it contains null on some other special events too.
There are 2 solutions.
Solution A:
1/ on the timer event: rise an user interface element event like click
2/ on an event handler for this element event: call __doPostBack
There is still a trap.
You may think that you can create an event objet and fire it on an element.
This would work, but window.event would still contain null.
It looks strange, but I suppose it is by design.
The only way to trigger an element event AND having window.event containing the event instead of null is to call this element click method.
Solution B:
If the UpdatePanel contains an input type="submit" element, there is no need to call __doPostBack to perform an asynchronous postback.
Calling this element click method is enought.
If the UpdatePanel contains no input submit element, the timer event handler can create one and use it:
var btn = document.createElement('INPUT');
btn.setAttribute('name', 'timer_dummy_button');
btn.setAttribute('type', 'submit');
btn.setAttribute('value', 'what you like');
btn.setAttribute('style', 'display:none;');
document.getElementById('yourNiceLittleUpdatePanelID').appendChild(btn);
btn.click();
On asynchronous postback, Page.Request.Form would contain these items :
["yourNiceLittleScriptManagerControlID"] = "yourNiceLittleUpdatePanelID|timer_dummy_button"
["__EVENTTARGET"] = ""
["__EVENTARGUMENT"] = ""
["timer_dummy_button"] = "what you like"
I don't think this Sys$WebForms$PageRequestManager$_doPostBack javascript code was done by any developer, I think that it's the ASP engine generates it. I think you should post the ASP code, maybe this userControlSearchResults_results function's code.
There are many posts on how to use __doPostBack. Check that you use it properly.
How to use __doPostBack()

whats wrong in this asp.net webusercontrol code?

I have updated my code but it still not working ...
after i run my asp.net webpage and click on button the following error occurs everytime ...
Microsoft JScript runtime error: Exception thrown and not caught
<%# Control Language="VB" AutoEventWireup="false" CodeFile="WebUserControl.ascx.vb" Inherits="WebUserControl" %>
<script src="./scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#chkAll').click(
function() {
$("INPUT[type='button']").attr('click', $('#chkAll').is(':click'));
});
});
</script>
<div>
<asp:Panel ID="Panel1" runat="server">
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:CheckBox ID="CheckBox3" runat="server" />
<br />
<br />
<br />
<input id="chkAll" type="button" value="button" />
</asp:Panel>
</div>
Microsoft JScript runtime error: Exception thrown and not caught
You don't need #<%=chkAll.ClientID %> for controls that don't have runat="server"
Just use the ID.
It looks like you're trying to do exactly what's being demonstrated here. From that demo:
$(document).ready(function()
{
$("#paradigm_all").click(function()
{
var checked_status = this.checked;
$("input[#name=paradigm]").each(function()
{
this.checked = checked_status;
});
});
});
Note the key differences between what this is doing and what your code is doing. You are selecting inputs of type button and trying to change a property on them called click. That... won't work. This demo is instead selecting some inputs of type checkbox by name and setting their checked status. Additionally, it's doing it by use of a checkbox rather than a button (which appears to be your stated intention).
You can read up on jQuery selectors here. There's a lot you can use for selecting elements. In the demo, the elements have the same name attribute and can be selected as such. You should be able to set name properties in your .NET server controls for use on client-side code just as easily. Without name attributes, you could alternatively select them child elements of your Panel, or your div, etc. You may want to give some names or ids in there just to make it easy on yourself.
Edit: Based on your comment, you can just change the logic a little bit. You'd still bind to the click event as before. However, you wouldn't be able to use the elements own checked status, since a button doesn't have one. Something like this, for example:
$(document).ready(function()
{
$("#paradigm_all").click(function()
{
$(":checkbox").each(function()
{
this.checked = true;
});
});
});
This modifies the logic of the previous example (assuming you've changed the target checkbox to a button in the markup). The main differences are:
The selector for the other checkboxes now selects all checkboxes on the page. You'll probably want to target a more specific selector than this, but it works for the purpose of the demo.
The button only sets all checkboxes to checked. With this example, clicking the button again doesn't un-check them. To accomplish that you'd have to define a bit more logic. For example, if some of them are checked and the button is clicked, do they all check or all un-check? Or do they toggle? What if the user uses the button to check all and then un-checks one? Upon clicking the button again, does the one get re-checked or do the rest get un-checked? Lots of UX questions :)

Microsoft JScript runtime error: Object required

I wrote a simple javascript function for validating to fields in a aspx page
function validate()
{
if (document.getElementById("<%=tbName.ClientID%>").value=="")
{
alert("Name Feild can not be blank");
document.getElementById("<%=tbName.ClientID%>").focus();
return false;
}
if (document.getElementById("<%=ddlBranch.ClientID%>").value=="SelectBranch")
{
alert("Branch Should Be Selected");
document.getElementById("<%=ddlBranch.ClientID%>").focus();
return false;
}
}
Everything worked fine.
Later I linked it to aspx page like a external js file.
head runat="server">
script src="validation.js" type="text/javascript">
/script>
<title>Validations</title>
/head>
<form id="form" runat="server">
<asp:Label ID="lblName" runat="server" Text="Nmae: ">/asp:Label>
<asp:TextBox ID="tbName" runat="server" Width="130px">/asp:TextBox>
<asp:Label ID="lblBranch" runat="server" Text="Branch:">/asp:Label>
<asp:DropDownList ID="ddlBranch" runat="server" Width="107px">
<asp:ListItem>CSE</asp:ListItem>
<asp:ListItem>ECE</asp:ListItem>
<asp:ListItem>CIVIL</asp:ListItem>
<asp:ListItem>MECH</asp:ListItem>
<asp:ListItem Selected="True" Value="SelectBranch">SelectBranch</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return validate(<%=tbName.ClientID%>, <%=ddlBranch.ClientID%>)" />
</form>
and
In aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
Page.RegisterClientScriptBlock("MyScript", "<SCRIPT Language='JavaScript' src='validation.js'></SCRIPT>");
btnSubmit.Attributes.Add("onclick", "return validate()");
}
Now its giving error "Microsoft JScript runtime error: Object required".
I'm unable to know where I went wrong.
Your script can only run inside the aspx page as it is. <%=tbName.ClientID%> is server-side logic it's placing the literal client-side ID in the output to the client, so before it looked like this when rendered in the HTML:
document.getElementById("tbName")
//looks for <input id="tbName" />
Now it looks just like this:
document.getElementById("<%=tbName.ClientID%>")
//looks for <input id="<%=tbName.ClientID%>" /> ... doesn't exist :)
Since it's no longer finding an object/element (because that ID doesn't exist) you're getting the object required error. You have to either keep this logic in the page, or move to some other approach using classes, etc. If you're doing a lot of validation, I'd take a look at jQuery and the validation library.
Update: Here's the solution T.J. provided for you in comments in full text form for an easier read. If you're only validating a few fields, this is the simplest fix to your situation:
function validate(nameId, branchId) {
if (document.getElementById(nameId).value=="")
{
alert("Name Feild can not be blank");
document.getElementById(nameId).focus();
return false;
}
if (document.getElementById(branchId).value=="SelectBranch")
{
alert("Branch Should Be Selected");
document.getElementById(branchId).focus();
return false;
}
}
In your code-behind:
//Note your current method is deprecated after .Net 2.0+, should use this instead:
//ClientScript.RegisterClientScriptInclude("validation", "validation.js");
Page.RegisterClientScriptBlock("MyScript", "<script type='text/javascript' src='validation.js'></script>");
btnSubmit.Attributes.Add("onclick", string.Format("return validate('{0}','{1}')", tbName.ClientID, ddlBranch.ClientID));
give the object you want to reference a html id which would output like
<div id="myid"></div>
than you can reference it by
document.getElementById("myid")

Categories

Resources