Can't call javascript function in ASP.NET cs page - javascript

I have below JavaScript function in my aspx page:
<script>
function ShowMessage() {
alert("Hello World");
}
</script>
I want to use this function in my cs page on button click event:
<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
Now this code works fine:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "alert('Hello World');", true);
But this code dose not work:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "ShowMessage();", true);
What's wrong in my code? What's the possible reason?

You need to expose your ShowMessage() function to a scope that your DOM has access to.
You can try:
window.ShowMessage = function() {
alert("Hello World");
}
Another option is to move your <script></script> containing your function ABOVE the DOM element that needs it:
<script>
function Foo() {
alert('Bar');
}
</script>
<button onclick="Foo()"></button>

You can use onclientclick
<asp:Button ID="MyButton" runat="server" Text="Click Here" onclientclick="ShowMessage()" />

Try this:
<script>
$('#idOfButton').click(
function() {
alert("Hello World");
}
);
</script>
Note: use JQuery for this code and paste this on the end of your HTML page.
Hope this will help

Related

How to call javascript function before ConfirmButtonExtender in asp.net?

I have a asp:Button, I want to call javascript function before ConfirmButtonExtender takes action. But my javascript code is not working. Please tell me how to use ConfirmButtonExtender with javascript.
<asp:Button ID="UpdatebuttonUpdaterID" runat="server" Text="Update" CssClass="create_role_button_in"
OnClick="UpdatebuttonUpdaterID_Click" OnClientClick="return OnClientClickUpdate();"/>
<ajaxToolkit:ConfirmButtonExtender ID="ConfirmButtonExtender3" runat="server" TargetControlID="UpdatebuttonUpdaterID"
ConfirmText="Do you want to send this Conversion Rate for Approval?" ConfirmOnFormSubmit="true" OnClientCancel="CancelClick"/>
This is my javascript code.
function OnClientClickUpdate() {
alert("hello");
}
You can use the Behavior property of the ConfirmButtonExtender and add the javascript function to it, this way the javascript function will be called before the ConfirmText property of the ConfirmButtonExtender.
Modify your markup to the following:
<asp:Button ID="UpdatebuttonUpdaterID" runat="server" Text="Update" CssClass="create_role_button_in"
OnClick="UpdatebuttonUpdaterID_Click" OnClientClick="return OnClientClickUpdate();"/>
<ajaxToolkit:ConfirmButtonExtender BehaviorID="confirmBehavior" ID="ConfirmButtonExtender3" runat="server" TargetControlID="UpdatebuttonUpdaterID"
ConfirmText="Do you want to send this Conversion Rate for Approval?" ConfirmOnFormSubmit="true" OnClientCancel="CancelClick"/>
<script type="text/ecmascript">
Sys.Application.add_load(wireEvents);
function wireEvents() {
var behavior = $find("confirmBehavior");
behavior.add_showing(OnClientClickUpdate);
}
function OnClientClickUpdate() {
alert("hello");
}
</script>
Hope it helps, source for this answer Here.
You can give up using the confirm extender (unlees you really need it) and use javascript:
function OnClientClickUpdate()
{
alert("first click");
//do some stuff
return confirm("are you sure?");
}

Calling the button.click() event from javascript doesn't fire

I have the following source in aspx:
<div>
<asp:HiddenField ID="hidValue" runat="server" />
<asp:Button runat="server" ID="hidButton" OnClick="hidButton_Click" />
<script type="text/javascript">
function ExtendPanel(PanelNumber) {
var hidValue = document.getElementById('<%=hidValue.ClientID %>');
hidValue.value = PanelNumber;
document.getElementById('<%=hidButton.ClientID%>').fireEvent("onclick");
}
</script>
</div>
In my code behind, I have the following C# function declared:
protected void hidButton_Click(object sender, EventArgs e)
{
int PanelNumber = int.Parse(hidValue.Value);
... do something with PanelNumber ...
}
When I click on the button using the mouse, "hidButton_Click" function is normally executed.
However, when the javascript function ExtendPanel(PanelNumber) is executed, the click event seems to be fired, but the function is not executed.
Replace this
document.getElementById('<%=hidButton.ClientID%>').fireEvent("onclick");
with
__doPostBack('hidButton','OnClick');
try this
document.getElementById('<%=hidButton.ClientID%>').click();
Try this one below
$('#<%=hidButton.ClientID%>').click();
I got the same issues and resolved to put
OnClientClick="javascript:return true;"

How to call javascript function from vbscript

how to call javascript function from vbscript.
i wrote like this
<script type="text/vbscript">
jsfunction()
</script>
<script type="text/javascript">
function jsfunction()
{
alert("Hello")
}
</script>
but it is showing that type mis match how to achieve it. please help me.
Thank you,
Mihir
Assuming you want this client side as opposed to ASP;
If you place the JScript block before the VBScript block (or wire the call to a load event) that will work fine. (IE only of course)
...
<head>
<script type="text/vbscript">
function foo
call jsfunction()
end function
</script>
<script type="text/javascript">
function jsfunction()
{
alert("hello");
}
</script>
</head>
<body onload="foo()">
...
Calling a VBScript function from Javascript
Your VBScript:
Function myVBFunction()
' here comes your vbscript code
End Function
Your Javascript:
function myJavascriptFunction(){
myVBFunction(); // calls the vbs function
}
window.onload = myJavascriptFunction;
Alternatives (incompatible in some IE versions):
// This one:
window.onload = function(){ myVBFunction(); }
// This will also work:
window.onload = myVBFunction();
// Or simply:
myVBFunction();
// From a hardcoded link, don't write a semicolon a the end:
link
Inversed:
Calling a Javascript function from VBScript
Function myVBFunction()
myJavascriptFunction()
End Function
Try this ...
<%# Language=VBScript %>
<HTML>
<HEAD>
</HEAD>
<BODY>
<script language="JavaScript" >
function jsfunction()
{
alert("Hello")
}
</script>
<%
Response.Write "Calling =" jsfunction() "."
%>
</BODY>
</HTML>
Instead of alert we should write return which is in turn print the values on page using response.write-
code is below -
<%# Language=VBScript %>
<HTML>
<HEAD>
</HEAD>
<BODY>
<script language="JavaScript" runat="server">
function test() {
return "Test";
}
</script>
<%
Response.Write "Value returned =" & test() & "."
%>
</BODY>
</HTML>

__doPostBack not working for me

Is there an error in the way i use the __doPostBack?
function displaymessage() {
var scl = "aaaaaa";
var pageId = '<%= Page.ClientID %>';
__doPostBack(pageId, 'OtherInformation');
alert(scl);
}
<input type="button" value="Click me!" id="Button2" onclick="displaymessage()" />
When i press the button it should call the RaisePostBackEvent in the code file, but it doesn't. If i comment the doPostBack it reaches the alert but when it is uncommented it does not. So it must be an error in the usage of the doPostBack.
I followed this post: Call ASP.NET function from JavaScript?
Place the following script on the header section of your html file:
<script>
function __doPostBack(eventTarget, eventArgument) {
document.Form1.__EVENTTARGET.value = eventTarget;
document.Form1.__EVENTARGUMENT.value = eventArgument;
document.Form1.submit();
}
</script>
for me the _dopostback() was not firing only on IE and chrome browser. I have resolved by adding "return false;" statement in the javascript function. for example:-
function test()
{
_dopostback("logout","");
return false;
}
now its working fine.
Change you code to this:
setTimeout(function () { __doPostBack('btnSave', '') }, 500);
Use btnSave Id. It will work in all browsers.
Drop your second argument of __doPostBack ('OtherInformation'), and replace with an empty string, ''. You could put that data in a hidden input field if you need it, and retrieve it using Request.Form.
I also followed the same post you mentioned and got an error, I tried to use the other answers here but it still didn't work.
Until I've found this post:
http://forums.asp.net/t/1197643.aspx
(look in the 8th reply made by NC01).
1.basically the idea is that your aspx should have something like this:
<script type="text/javascript" language="javascript">
function myfunction() {
if ('<%=Page.IsPostBack%>' == 'False') {
var pageId = '<%= this.UniqueID %>';
__doPostBack(pageId, 'do_something_good');
}
}
</script>
2.then in your .cs you should add interface IPostBackEventHandler (for example:)
public partial class _default : System.Web.UI.Page, IPostBackEventHandler
3.and in your .cs in page_load add this line:
this.ClientScript.GetPostBackEventReference(this, string.Empty);
4.don't forget to implement the interface:
public void RaisePostBackEvent(string eventArgument)
{
if (eventArgument == "do_something_good")
{
//bla
}
}
And guess what - it even works!
#Subhash Dike - The PageMethods works only for static methods, AFAIK.
Add EnableEventValidation="false" into your <%Page tag to solve __doPostBack problem

Javascript error: function XXXX() not defined

I added a javascript function in a page
<head>
<script type=text/javascript>
function show_Alert(error)
{
alert(error);
}
</script>
</head>
and on button click I am doing this
Protected void btn_Click(object o,Eventargs e)
{
StringBuilder str = new StringBuilder();
str.AppendLine("show_Alert('XYZ error')");
ClientScript.RegisterStartupScript(GetType(),"Alert",str.ToString(),true);
}
But it throws JS error show_Alert is not defined :(
Any Idea, what is wrong here??
Thanx
Your script tag is wrong.
Change it to
<script type="text/javascript">
However, I don't think that's the issue.
I suspect that RegisterStartupScript is emitting its <script> block before the one with your function, so that it ends up calling the function before it exists.
Check where each <script> is in the rendered source.
Make sure your <script> element is valid, like this:
<head>
<script type="text/javascript">
function show_Alert(error)
{
alert(error);
}
</script>
</head>
If it's not well formed, or the type is unrecognized (your case has both) then the script inside will be ignored, since the browser doesn't know how to handle it.
Here's an example:
<%# Page Language="C#" %>
<script type="text/C#" runat="server">
protected void BtnClick(object sender, EventArgs e)
{
var str = "XYZ Error";
var script = new StringBuilder();
script.AppendFormat("showAlert('{0}');",
HttpUtility.JavaScriptStringEncode(str)
);
ClientScript.RegisterStartupScript(GetType(), "alert", script.ToString(), true);
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function showAlert(error) {
alert(error);
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<asp:LinkButton ID="Btn" runat="server" Text="Click me" OnClick="BtnClick" />
</form>
</body>
</html>
A very important thing to pay attention to is to properly encode the string you are passing to the showAlert function. Notice that it is encoded:
script.AppendFormat("showAlert('{0}');",
HttpUtility.JavaScriptStringEncode(str)
);
If you don't encode it and the string contains some special characters like ' for instance, your script will break.

Categories