Javascript alert before a event call not firing - javascript

strScriptString = "alert('Hello');";
ScriptManager.RegisterStartupScript(Page, this.GetType(), "Startup", strScriptString, true);
btn_Click(this, null);
The alert is not showing up :(
please help

You need to still put the script tags around your alert:
strScriptString = "<script>alert('Hello');</script>";
EDIT
My mistake, read the wrong RegisterStartupScript class

Have you checked the source of the page for the script using Firebug? I'll hazard a guess that if you remove btn_Click(this, null); it may work.

You can add following code snippet into page_Load..
btnUpdate.Attributes.Add("onclick", "GetAlert();");
Button Click event in code behind.
protected void btnUpdate_Click(object sender, EventArgs e)
{
btnUpdate.Text = "Reload";
}
Button in aspx page
<asp:Button ID="btnUpdate" runat="server" Text="Submit" OnClick="btnUpdate_Click"/>
Javascript for alert
<script>
function GetAlert() {
alert("123");
return true;
}
</script>

If you're looking to show an alert before the server-side event fires, use OnClientClick, and return true.
<asp:Button ID="Button1" runat="server" OnClientClick="alert('Hi!');return true;" ... />

Related

C# method skipping over java script call

I have an ASP button that has an event listener attached to it. When pressed it calls the C# method and executes whatever code I may have within it.
I have a javascript function I want to call when the listener first executes. However, C# completely skips over the function call and moves on to the lines below it.
Here's the question: Why is it skipping over the call? And when I isolate just the call, ( have nothing in the method other than the call) IT WORKS. The very second I put another line of code below it, it stops being called. Any help would be greatly appreciated.
Here is the ASP button.
<asp:Button ID="crapJim" runat="server" Text="RateTest" OnClick="crapJim_Click"/>
And here is the C# Method
protected void crapJim_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "getSessionName()", true);
/* ClientScript.RegisterStartupScript(GetType(), "hwa", "getSessionName();", true);*/
string s = hfRaterName.Value;
Console.Write(s);
string stop = "";
}
Currently have the ClientScript commented out and trying the ScriptManager. Both work individually, but not when other code is with it. What I mean by that is:
protected void crapJim_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "getSessionName()", true);
}
Just this alone will work, but any other code with it, it will no longer fire. C# skips over it.
Oh and here is the Javascript code I am using.
function getSessionName() {
var hfRaterName = prompt("Please enter your session name");
hfRaterName.value = hfRaterName;
}
There's an easier way, if you don't have to use RegisterStartupScript.
.aspx:
// OnClientClick will call your javascript function first, then the code behind.
<asp:Button ID="btnPrompt" runat="server" Text="Prompt"
OnClientClick="doPrompt();"
OnClick="btnPrompt_Click" />
<br />
<asp:Label ID="lblPromptResult" runat="server"></asp:Label>
<br />
<asp:HiddenField ID="hfPrompt" runat="server" />
<br />
<script>
function doPrompt() {
document.getElementById("hfPrompt").value =
prompt("Please enter your session name");
}
</script>
Code behind:
protected void btnPrompt_Click(object sender, EventArgs e)
{
lblPromptResult.Text = hfPrompt.Value;
}
In the case anyone else comes across this same problem. I took wazz's advice and used the OnclientClick along with Onclick. Executing the Javascript first rather than having the C# call the Javascript.
//This is the HiddenField used to capture the users identified session name
//which I then store in a DB and use in a few other related pages.
<asp:HiddenField ID="HiddenField1" ClientIDMode="Static" runat="server" />
//This is the ASP button used to call both the Javascript and C# code behind
<asp:Button ID="btnRateBeazely" ClientIDMode="Static" runat="server" CssClass="btnbig" Text="Rate Beazley" OnClick="btnRateBeazely_Click" OnClientClick="getSessionName();" />
//The Javascript is simple, but does exactly what I want it to. DB has character
//limit to 50 so I ensure the user can't input higher than that. Assign the input
//to the hiddenfield ID and off we go.
function getSessionName() {
var SessionSet = prompt("Please enter your session name");
while (SessionSet.length > 49) {
alert("You have too many characters. Please enter again.")
var SessionSet = prompt("Please reenter your session name");
}
document.getElementById("HiddenField1").value = SessionSet;
}
//In the code behind I just assign a new string variable to the hidden field value

How to get confirmation of an action in a web page?

On an ASPX page I have a "Delete" button that is wired up to a method that calls for the current record to be deleted. The button is wired up in this way:
<asp:Button ID="btnDeleteUser" runat="server" Text="Delete" OnClick="btnDeleteUser_Click" />
protected void btnDeleteUser_Click(object sender, EventArgs e)
{
DeleteUser();
}
I want to interrupt the delete action with a confirmation dialog, and if it is confirmed then the delete method is called. Presumably I would put an OnClientClick method in there.
OnClientClick="confirmDelete();"
<script type="text/javascript">
function confirmDelete(){
var msg = "This will delete this AR Contact. Are you sure you wish to do this.";
if (confirm(msg)){
// Do something here that causes the delete method on the server to be called
}
}
</script>
This raises an OK/Cancel dialog, and clicking Cancel obviously leads to nothing happening, but what if OK is clicked? How is the Delete method on the server to be called? I suppose that I could do a window.open onto a page that did the actual delete, and I can do that, but is there a way to submit to the server-side delete method from JavaScript?
<script type="text/javascript">
function confirmDelete(){
var msg = "This will delete this AR Contact. Are you sure you wish to do this?";
return confirm(msg);
}
</script>
And make sure this attribute is on your button.
OnClientClick="return confirmDelete();"
Confirm returns true if the user clicks yes. It returns false if the user hits no. So you just return that, and it will automatically proceed to the server side function if the client side function returned true.
The javascript confirm will not call the server method if the user cancels. If the user clicks ok, the javascript confirm would allow the button to send its request to the server.
You don't need to worry about opening a new page, etc.
Sample 1:
<asp:Button ID="btnDeleteUser" runat="server" Text="Delete" OnClick="btnDeleteUser_Click"
OnClientClick="return confirm('This will delete this AR Contact. Are you sure you wish to do this?');" />
And leave your server-side code the same.
protected void btnDeleteUser_Click(object sender, EventArgs e)
{
DeleteUser();
}
Sample 2:
If you have multiple items that can raise the same confirmation message, go ahead and do it the way you had it. However, it would look like this:
<asp:Button ID="btnDeleteUser" runat="server" Text="Delete" OnClick="btnDeleteUser_Click"
OnClientClick="return confirmDelete();" />
And the javascript:
<script type="text/javascript">
function confirmDelete(){
var msg = "This will delete this AR Contact. Are you sure you wish to do this.";
return confirm(msg);
}
</script>
When you return the confirm's result, it should be seen by ASP.NET's postback javascript. If confirm or your confirmDelete method returns false, then the postback should be skipped.

Referencing inline scripts from update panels in ASP.NET

I am trying to work around an issue with using inline scripts in update panels. The issue is something I might commonly solve by using Sys.Application.add_load() or creating a RegisterStatupScript() script with the ScriptManager. However, neither solution works in this case.
Here is the problem.
Update panel on asp.net (in this case, SharePoint) page:
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Load" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
Lets say in the code behind we add a user control to the placeholder when the button is clicked.
protected void Button1_Click(object sender, EventArgs e)
{
MyControl ctrl = new MyControl();
PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(ctrl);
UpdatePanel1.Update();
}
Finally, let's say our user control has some inline scripts.
<script type="text/javascript">
var myInt = 1;
alert(typeof myInt);
</script>
Putting the above together and running it would lead to an update panel that is empty (except the button) by default- get's some data added when the button is clicked that looks like the javascript above. The problem is the javascript code above will never fire.
In my real life case the user control is not terribly complex- it has a repeater that is populated when the control is loaded then some inline javascript which transforms the repeater data a bit. The data comes through but the javascript is never executed and throws no errors.
Attempted solution:
Wrap inline javascript in a function called initMyCode() then use:
ScriptManager.RegisterStartupScript(this, this.getType(), UniqueID, "initMyCode()", true);
...on the user control page load event. This fails as initMyCode() cannot be found within the page.
Anyone have a workable solution for this issue?
if(!Page.ClientScript.IsStartupScriptRegistered("initMyCode")){
string script =#"function initMyCode(){var myInt = 1;
alert(typeof myInt);}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(initMyCode);"
ScriptManager.RegisterStartupScript(this, this.getType(), initMyCode, script, true);
}
Or
<script type="text/javascript">
function initMyCode(){
var myInt = 1;
alert(typeof myInt);}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(initMyCode);
</script>
Have you already tried adding your code in the "ready" of jQuery?

How to fire a button click event from JavaScript in ASP.NET

How do I fire a server side button click event from JavaScript?
I tried like this:
document.getElementById("<%= ButtonID.ClientID %>").click();
But no use. How can I do it?
You can just place this line in a JavaScript function:
__doPostBack('btnSubmit','OnClick');
Or do something like this:
$('#btnSubmit').trigger('click');
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
That solution works for me, but remember it wont work if your asp button has
Visible="False"
To hide button that should be triggered with that script you should hide it with <div hidden></div>
I used the below JavaScript code and it works...
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
None of the solutions posted here would work for me, this was my eventual solution to the problem.
// In Server Side code
protected void Page_Load(object sender, EventArgs e)
{
Page.GetPostBackEventReference(hiddenButton);
}
// Javascript
function SetSaved() {
__doPostBack("<%= hiddenButton.UniqueID %>", "OnClick");
}
// ASP
<asp:Button ID="hiddenButton" runat="server" OnClick="btnSaveGroup_Click" Visible="false"/>
I lived this problem in two days and suddenly I realized it that I am using this click method(for asp button) in a submit button(in html submit button) javascript method...
I mean ->
I have an html submit button and an asp button like these:
<input type="submit" value="Siparişi Gönder" onclick="SendEmail()" />
<asp:Button ID="sendEmailButton" runat="server" Text="Gönder" OnClick="SendToEmail" Visible="True"></asp:Button>
SendToEmail() is a server side method in Default.aspx
SendEmail() is a javascript method like this:
<script type="text/javascript" lang="javascript">
function SendEmail() {
document.getElementById('<%= sendEmailButton.UniqueID %>').click();
alert("Your message is sending...");
}
</script>
And this "document.getElementById('<%= sendEmailButton.UniqueID %>').click();" method did not work in just Crome. It was working in IE and Firefox.
Then I tried and tried a lot of ways for executing "SendToEmail()" method in Crome.
Then suddenly I changed html submit button --> just html button like this and now it is working:
<input type="button" value="Siparişi Gönder" onclick="SendEmail()" />
Have a nice days...
I can make things work this way:
inside javascript junction that is executed by the html button:
document.getElementById("<%= Button2.ClientID %>").click();
ASP button inside div:
<div id="submitBtn" style="display: none;">
<asp:Button ID="Button2" runat="server" Text="Submit" ValidationGroup="AllValidators" OnClick="Button2_Click" />
</div>
Everything runs from the .cs file except that the code below doesn't execute. There is no message box and redirect to the same page (refresh all boxes):
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
cmd2.CommandText = insertSuperRoster;
cmd2.Connection = con;
cmd2.ExecuteNonQuery();
string url = "VaccineRefusal.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Data Inserted Successfully!');window.location.href = '" + url + "';", true);
}
Any ideas why these lines won't execute?
You can fill a hidden field from your JavaScript code and do an explicit postback from JavaScript. Then from the server side, check that hiddenfield and do whatever necessary.
document.FormName.btnSubmit.click();
works for me. Enjoy.
$("#"+document.getElementById("<%= ButtonID.ClientID %>")).trigger("click");
The issue I had was the validation group that was not specified.
I added ValidationGroup="none" as per below and it worked.
<asp:Button ID="BtnQuickSearch" runat="server" Text="Search"
OnClick="BtnQuickSearch_Click" ValidationGroup="none" />
I must mention that I had 2 other forms with buttons on the page, both had their own validation groups specified. This button had did not have a validation group specified and the onclick event simply did not fire.

Please find the error in below written code for asp + JavaScript

<script type=text/javascript>
function abc()
{
return confirm('Are u sure');
}
</script>
<asp: Button id="btnSubmit" runat="server" onClick="btnSubmit_Click" onClientClick="abc" Text="Submit/>
When I click the button the message box appears if I hit the cancel Button still the function for onClick is called instead it should not.
But if I write JavaScript code directly in the tag it works properly.
onClientClick="return abc()"
the return is the essential bit.

Categories

Resources