OnClientClick event in In ASP.NET - javascript

I'm using ASP.NET to pass a value to a JavaScript function and, for some reason I haven't been able to determine, it isn't working when I try to pass in a value from another control. Instead, it acts like there is a syntax error and it just submits back to the main form.
Does anyone know why?
Example:
<asp:TextBox ID="txtToSay" runat="server" Text="Something"></asp:TextBox>
<asp:Button runat="server" ID="btnSaySomething1" Text="Say Something"
OnClientClick="saySomething(<%=txtToSay.Text%>);" /> <!-- doesn't work -->
<asp:Button runat="server" ID="btnSaySomething1" Text="Say Something"
OnClientClick="saySomething('<%=txtToSay.Text%>');" /> <!-- doesn't work -->
<asp:Button runat="server" ID="btnSaySomething2" Text="Say Something"
OnClientClick="saySomething('Something');" /> <!-- works -->
<script type="text/javascript">
function saySomething(txt){
alert(txt);
};
</script>
Additional Information:
Web Application running on .NET 4.0
Language: C#
Update:
After working with this a while, I've determined that you can't use <%%> tags in ASP controls. Additionally, if you're looking for dynamic evaluation of control values AVOID AVOID AVOID using <%=someControl.Text%> or similar constructs since they are only evaluated once a request is submitted to the server. If you need a static value from another control at runtime, simply set that value in the page load event or handle it another way in the code behind.

Javacript will search for variable name = txtToSay.Text in saySomething function call, Put quotes around it to make it string value
Change
OnClientClick="saySomething(<%=txtToSay.Text%>);"
To
OnClientClick="saySomething('<%=txtToSay.Text%>');"
You can get the txtToSay.Text without passing it this way
<script type="text/javascript">
function saySomething(txt){
alert(document.getElementById('<%=txtToSay.Text%>').value);
};
</script>

you need to put ' around your text in the saySomething() call.
Like this:
<asp:Button runat="server" ID="btnSaySomething1" Text="Say Something" OnClientClick="saySomething('<%=txtToSay.Text%>');" />
UPDATE
<%= %> won't work inside an asp.net control. Can you set it from the code-behind?
I.E
btnSaySomething1.OnClientClick = "Text to say"

Related

how to open an aspx page as popup on button click

I have created an aspx page "Analyse.aspx", I want to pass an argument to this page when calling it on a button click of another page say 'Master.aspx' by-
OnClientClick="javascript:window.open('Analyse.aspx?Param=');"
how to do it?
"Could not load type" can happen due to various reasons and not because of popup. Try to call Analyse.aspx directly in your browser and make sure it works. To troubleshoot read Parser Error Message: Could not load type 'webmarketing'
UPDATE
Your code is not well formed.
Instead of
OnClick="javascript:window.open(Analyse.aspx?Param=""');"
must be
OnClick="javascript:window.open('Analyse.aspx?Param=');"
UPDATE #2
To wire a js code to js onclick event you should use the OnClientClick() event
<asp:Button ID="btnDeDupCheck" runat="server"
OnClientClick="javascript:window.open('PieChart.aspx?Param=');"
Text="De-Duplication Check" Visible="False" />
The OnClick() event is used to run a .net code.
UPDATE #3
To add values from asp.net controls you need to inject asp.net code. Read How to pass a value into a javascript function within an aspx page onClientClick or OnClientClick Javascript:confirm get value in textbox?
<asp:Button ID="btnDeDupCheck" runat="server"
OnClientClick="javascript:window.open('PieChart.aspx?Param=<%=txt1.ClientID%>');"
Text="De-Duplication Check" Visible="False" />
I finally got the it,successful executed code-
OnClientClick="javascript:window.open('Analyse.aspx?Param=');"
but my new query is how to pass parameter from current page to this new page 'Analyse.aspx',
say my parameter is - "txtPwd.text"
and how to catch the argument on pageload of Analyse.aspx

ddl is not updated in server - asp.net

I work on ASP.NET c#. I have a DropDownList. (runat="server")
On $(document).ready, I updated its value:
$(document).ready(function () {
document.getElementById("ddl").value = "abc";
…
When I get back to the Server (c#), there is no value in the ddl:
ddl.SelectedValue == ""
What could be the problem?
Thanks,
YYY
as far your dropdown runat="server" it has generated ClientID, "ddl" it's serverside id, on client you need to call like shown below
document.getElementById("<%= ddl.ClientID %>").value = "abc";
Welcome to the wonderful world of WebForms: in the list of things this framework screws up is ID's of your runat="server" elements
When the engine processes your server markup it generates own id's based on the place where you declared that particular element. Check it in your browser devtools.
Luckily since ASP.NET 4 you can specify special attribute ClientIDMode and now you can do it like
<asp:TextBox ID="txt" runat="server" ClientIDMode="Static" />
which will render like
<input id="txt" name="ctl00$MasterPageBody$ctl00$txt" />
If you cannot use for some reason ASP.NET 4, you can stick to old solution as #Dan proposed:
document.getElementById("<%= ddl.ClientID %>")
But this is not the recommended way.
EDIT
Probably you should do ddl.SelectedItem.Value instead.

Converting aspx page to WebUserControl

I am running into an issue when converting an ASPX page to a controller (ASCX). My JavaScript isn't finding a textbox in a hidden div and its not firing an onclick event either. However it works perfectly fine in the ASPX page.
My JavaScript is..
function FireEditClickButton() {
document.getElementById("btnFireEdit").click();
}
Its supposed to fire this button that is in a hidden div along with the next piece)
<asp:Button ID="btnFireEdit" runat="server" OnClick="btnFireEdit_Click" />
Then with this JavaScript
function GetSelection() {
var c = document.getElementById("tbRA");
c.innerText = checkListBox.GetSelectedValues();
UpdateText();
}
gets called everytime the checklistbox has values.
Both errors are saying that they are null but they are right here in a hidden div
<div style="visibility: hidden">
<asp:TextBox ID="tbRA" runat="server"></asp:TextBox>
<asp:Button ID="btnFireEdit" runat="server" OnClick="btnFireEdit_Click" />
</div>
So why would this be happening since it works completely fine in the ASPX page? would it have to do with the WebUserControl not using a form tag?
Thanks
Your javascript cannot find the button because in the rendered HTML it no longer has id="btnFireEdit" but instead an id based on the name of the usercontrol (e.g. id="myctrlname_btnFireEdit").
You have two choices... either update the javascript to include the name of the usercontrol...
document.getElementById("myctrlname_btnFireEdit").click();
document.getElementById("<%=btnFireEdit.ClientID%>").click();
(Note, the 2nd of these two lines will only work if the javascript is part of the usercontrol itself. It will not work if the javascript is in an external .js file or the parent page)
Or use the ClientIDMode attribute of the <asp:Button> and set the value to Static. This will make the rendered HTML use id="btnFireEdit"...
<asp:Button ID="btnFireEdit" runat="server" OnClick="btnFireEdit_Click"
ClientIDMode="Static" />
When using nested controls (or pages nested in a master page), by default the ID on the client side will be different than on the server. ASP.NET does this by default to help ensure that all ID's on the client are unique. However, you can prevent this using one of two ways.
The first option is to change the ClientIDMode to static. You can do this at the control, page, web.config, or machine.config levels. The web.config technique is shown below. The ID on the client will then match the ID on the server.
<configuration>
<system.web>
<pages clientIDMode="static" />
</system.Web>
</configuration>
The second option is to use inline C# code to embed the ID into your JavaScript, but this only works if the JavaScript is embedded on an ASP.NET page or control and not in a separate script file. The C# expression will be evaluated and therefore the ID on the client will be embedded into the JavaScript.
document.getElementById('<%= btnFireEdit.ClientId %>');
There is a third option, and that is to figure out what the ID will be on the client and then manually put that in the JavaScript, like this:
document.getElementById("myctrlname_btnFireEdit").click();
However, that is a bad idea. If you ever rename either myctrlname or btnFireEdit then your client side code will fail at runtime. And it's always better to fail at compile time than runtime.

Passing values from javascript to code behind in ASP.NET

I have a variable in aspx.cs when I click the Datagrid particular row;
Then from the javascript, I should get that value and pass into aspx.cs variable.
how to do this?
Using html controls
First you use a hidden input control as:
<input type="hidden" value="" id="SendA" name="SendA" />
Second you add to that control the value you like to send on code behind using javascript as:
document.getElementById("SendA").value = "1";
And then on post back you get that value as:
Request.Form["SendA"]
Using asp.net Controls
The same way if you use asp.net control can be as:
<asp:HiddenField runat="server" ID="SendA" Value="" />
<script>
document.getElementById("<%=SendA.ClientID%>").value = "1";
</script>
and get it on code behind with SendA.Value;
And of course you can use ajax calls to send on code behind values, or simple call url with url parameters that return no content.

$find() return null for defined ajax behaviour

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>

Categories