Microsoft JScript runtime error: Object required - javascript

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")

Related

How to pass data from (front-end) .aspx to (back-end) .aspx.cs using hidden filed

I want to pass data from back-end to front-end and front-end to back-end so far I have tried like below
back-end to front-end :-
back-end (.aspx.cs):-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
}
front-end (.aspx):-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert(amt); // data coming
</script>
</form>
</body>
The above example is working fine but while passing the value from front-end to back-end I'm getting the null("") value (for this concept I have read this article)
front-end to back-end :-
front-end (.aspx) :-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert("amt :- " + amt);
function getval() {
var keyid = "1234";
document.getElementById('key_id').value = keyid;
alert(document.getElementById('key_id').value);
alert('hit');
window.location.href = "http://localhost:49855/ValuePassig.aspx";
}
//alert(amt);
</script>
<input id="key_id" runat="server" type="hidden" name="key_id_1" />
<input type="button" id="btn" value="click" runat="server" onclick="getval()" />
</form>
</body>
back-end(.aspx.cs) :-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
//I'm getting the null("") value
//string kId = this.Request["key_id_1"];
//string kId = Request.Form["key_id_1"];
string kId = key_id.Value; //Initially the value come null(acceptable) and next I'm clicking on the "click" button at that time null value should not come(but coming)
Response.Write(kId);
}
I did my best so far to achieve this concept and I don't why I'm getting a null value because, I have followed the article also(above mentioned link) to achieve this
concept
Suggest me where I did the mistake to pass the value from front-end to back-end and how to achieve this
Please give me your best suggestions.
Note :- I have changed the code for better understanding that is button added and when I click on the button the hidden value should come back-end.
Ok, so we want to have some value - set in code behind cs, to set/pass/have some value for use in the client side js code.
And of course in the js code, we want use of that value, and ALSO to be able to change that value, and then upon actions, or code behind, we want that value passed back to the code behind.
First up, don't use a server side expression to "set" that value for use in the js code. The reason of course then you don't have a easy way to pass back and have use of that change value in the code behind.
You can freely change the var in js code, but you really don't have a easy/nice way to get that value back to the code behind (so that <%= %> expression is a one way street to the client side.
There are a LOT of ways to do this, but probably best is to drop in a hidden field control (as per your question title)..
You can also use a hidden text box, but might as well use the hidden field.
So, lets on page load (and ONLY first page load - like all setup on the page should be inside of the !IsPostBack code block - all web pages quite much need this !IsPostBack code block).
And bonus?
the Hidden field control has automatic view state. (that means the value will persist on page post-backs).
So, lets drop in a server side button to "show" the value.
And THEN lets drop in a button (client side) to show the value, and ALSO to modify the value.
<asp:HiddenField ID="MyHotelName" runat="server" ClientIDMode="Static" />
<h3>Server side code</h3>
<asp:Button ID="cmdShowServer" runat="server" OnClick="cmdShowServer_Click"
Text="Show Hotel Name" CssClass="btn" />
<br />
<asp:Label ID="lblShow" runat="server" Text="Label"></asp:Label>
<h3>Client side code</h3>
<asp:Button ID="cmdShowClient" runat="server" Text="Show Hotel Name"
OnClientClick="ShowHotel();return false" />
<br />
<asp:Button ID="cmdChangeClient" runat="server" Text="Change Hotel Name"
OnClientClick="ChangeHotel();return false" />
<script>
function ShowHotel() {
alert("Hotel name = " + $("#MyHotelName").val())
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
$("#MyHotelName").val(sHotelNew)
}
</script>
And our code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MyHotelName.Value = "Zoo";
}
}
protected void cmdShowServer_Click(object sender, EventArgs e)
{
lblShow.Text = "Value of hotel = " + MyHotelName.Value;
}
So, we now have this:
Edit: Above used jquery.
Of course the js code above used jQuery.
however, we could assume pure js code, no jQuery.
so, the js code would then become this:
<script>
function ShowHotel() {
sHotel = document.getElementById("MyHotelName").value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById("MyHotelName").value = sHotelNew
}
</script>
I should also point out the "very" imprortant adding of clientidmode="static" for the hidden field. This will "prevent" asp.net system from changing the "id" used for the control, and as a result, the js code tends to be more "clean" and "easy" to reference controls.
If you don't want to use clientidmode=static for the hidden field, then the above code then becomes this:
hidden field thus is this: (no client id mode).
<asp:HiddenField ID="MyHotelName" runat="server" />
And now our code becomes this:
<script>
function ShowHotel() {
sHotel = document.getElementById('<%= MyHotelName.ClientID %>').value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById('<%= MyHotelName.ClientID %>').value = sHotelNew
}
</script>
So, I often will toss in a ClientIDMode="static" for the hidden field, as that makes the js code to get the hidden control less messy.

Send Command.Value via Javascript to codebehind

I am fairly new to ASP.Net and I am stuck.
If my Hyperlink is clicked a Command.Value should be sent to the server. After getting that Command.Value the code behind should check if it is right and redirect to a specific site otherwise just reload the page.
Here is my Hyperlink:
<asp:HyperLink
ID="Link"
runat="server"
Visible="true"
NavigateUrl="javascript:document.FormServer.Command.value =
'test';document.FormServer.submit();"
>Test!!</asp:HyperLink>
First of all I want to ask if my Hyperlink is right. Furthermore I am a bit stuck on the code behind regarding where I need to insert my If statement.
I believe it's much easier to send a parameter by GET in the url of your link. But if for any reason you want to do it by post and using javascript then try this.
Web form: param1 is a hidden field which value will be set using Javascript. When the form is submitted the hidden field is posted with the form.
<form id="FormServer" runat="server" >
<input type="text" id="param1" name="param1" style="display:none;" />
<div>
<asp:HyperLink
ID="Link"
runat="server"
Visible="true"
NavigateUrl="javascript:document.getElementById('param1').value = 'test';document.forms['FormServer'].submit();"
>Test!!</asp:HyperLink>
</div>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
string param1Value = Request["param1"];
if (param1Value == "test")
Response.Redirect("~/Default.aspx");
else if(param1Value == "lost")
Response.Redirect("http://www.google.com");
}
In the code behind it might be useful to check this.IsPostBack. That tells you why the page is being loaded. If it's because the link was clicked then IsPostBack will be true.

ASP Textbox default invisible and visible from JS

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(){...});

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()

Send JavaScript variable to asp.net webforms code-behind is always empty

I was using this SO answer as a reference for sending a JavaScript variable to my server side. However when I implement that solution everything comes up correctly in the JS alert(), but the value of my hidden field when I hit the server is always empty.
JavaScript and Html:
<script>
function rblSelectionChange()
{
var selection = $('#inAction input:checked').val();
var stuff = $('#<%= clientSelection.ClientID %>').val(selection);
alert(stuff.val());
}
</script>
<asp:HiddenField ID="clientSelection" runat="server" />
<div class="row-fluid">
<asp:RadioButtonList runat="server" ID="inAction" ClientIDMode="Static">
<asp:ListItem onClick="rblSelectionChange();" Value="RuEp" Text="I remember my <b>username</b>. Please email me a new <b>password</b>." />
<asp:ListItem onClick="rblSelectionChange();" Value="ReEu" Text="I remember my <b>email</b>. Please email me my <b>username</b>." />
<asp:ListItem onClick="rblSelectionChange();" Value="ReEup" Text="I remember my <b>email</b>. Please email me my <b>username</b> and a new <b>password</b>." />
</asp:RadioButtonList>
</div>
On the submit event of the page I try to grab the value and it is empty:
protected void btnActionSelect_Click(object sender, EventArgs e)
{
string selection = clientSelection.Value;
...snip...
}
Any idea what I am missing?
Update
I have tried to change my hidden field to a pure html one, not the asp: control.
<input type="hidden" id="clientSelection" name="clientSelection" value="" />
I have modified the code-behind as follows:
private string _selection = "";
protected void Page_Load(object sender, EventArgs e)
{
//_selection = clientSelection.Value.ToString();
if (IsPostBack)
_selection = Request.Form["clientSelection"];
}
I am still getting nothing for the value Request.Form["clientSelection"]. Important note however is it works in Chrome, FF, and IE10. The browser I am trying to get it to work in is IE 7 8 and 9. I am fully stumped.
Update 2
Per request, here is the source of the page when I inspect it in IE10 (with browser and document mode set to IE7)
<DIV id=ctl00_cphBodyWithForm_htmActionSelect class=row-fluid>
<P class=lead>Can't access your account? Please select from the following options: </P>
<SCRIPT>
function rblSelectionChange()
{
var selection = $('#inAction input:checked').val();
var stuff = $('#ctl00_cphBodyWithForm_clientSelection').val(selection);
alert(stuff.val());
}
</SCRIPT>
<INPUT id=ctl00_cphBodyWithForm_clientSelection type=hidden name=ctl00$cphBodyWithForm$clientSelection jQuery191034119593101524303="7">
<DIV class=row-fluid>
<TABLE id=inAction border=0>
<TBODY>
<TR>
<TD><INPUT onclick=rblSelectionChange(); id=inAction_0 type=radio value=RuEp name=ctl00$cphBodyWithForm$inAction jQuery191034119593101524303="8"><LABEL for=inAction_0>I remember my <B>username</B>. Please email me a new <B>password</B>.</LABEL></TD>
</TR>
...snip...
</TBODY>
</TABLE>
</DIV>
<DIV class=span12>
<A class="submitButton roundedBR" href="javascript:__doPostBack('ctl00$cphBodyWithForm$ctl00','')">Continue > </A>
</DIV>
</DIV>
Run your HTML through a validator. If your form values aren't posting in certain browsers, it sounds like you have invalid HTML, and that is the source of your problem.
Once you fix the HTML issue, you can get rid of that JavaScript and simply use the value of inAction.
W3C Markup Validation Service
You mentioned that you had weird closing form tag issues. A form cannot be placed within a form, so perhaps that was the root of your problem.

Categories

Resources