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

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.

Related

How to raise click event of a client side `reset ` button from code behind in asp.net?

I am trying to raise click event of
<input type="reset" id="btnreset" class="ButtonText"/>
using (in code behind):
ScriptManager.RegisterStartupScript(this, this.GetType(), "pop", "<script>alert('" + ds.Tables[0].Rows[0][0].ToString() + "'); document.getElementById('btnreset').click();</script>", false);
EDIT:
ScriptManager.RegisterStartupScript(this, this.GetType(), "pop", "<script>function myFunction() { alert('" + ds.Tables[0].Rows[0][0].ToString() + "'); document.getElementById('btnreset').click(); }</script>", false);
There are no errors in console. But it doesn't work......
You are trying to reset form that is not set (changed) yet.
You are resetting form on page load that wont have any effect as reset will reset the form values to the one that you have when page is loaded.
To see the effect of reset you should change the control the form control values first and then reset the form.
You probably need to initialize the value e.g. setting the all textboxes to blank etc.
You can better understand with this example.
Live Demo
<form id="frm">
<input value="123" />
<input type="button" id="btn" onclick="myfun();" />
</form>
document.getElementById('frm').reset();
alert("resetting form wont make the textbox empty on load");
function myfun(){
document.getElementById('frm').reset();
}
Here we are reset form on load with no effect but if we change the value in textbox and reset the form using button the initial value of textbox will be restored.
To initialize value of inputs you can do something like
$('input:text').val('');
$(':checkbox').prop('checked', false);
If you want to initial the form to the state that is at the first load then you can use Response.Redirect on the postback. It will initialize the form controls with minimum effort. You can use some session to show some message when page loads after redirect e.g showing that previous record saved successfully. You should not redirect in case of failure.
This is because your script is possibly executing before document loads,
Try,
ScriptManager.RegisterStartupScript(this, this.GetType(), "pop", "<script>function myFunction() { alert('" + ds.Tables[0].Rows[0][0].ToString() + "'); document.getElementById('btnreset').click(); }</script>", false);
And call this function when documents loads like,
<body onload="myFunction()">
Or you can do it in JavaScript code too,
window.onload="myFunction()";
Hope it helps, thanks.
<head runat="server">
<title></title>
<script type="text/javascript">
function YorFnName(str) {
alert(str);
return false;
}
</script>
<body>
<form id="form1" runat="server">
<div>
<input type="reset" runat="server" id="btnreset" class="ButtonText" />
</div>
</form>
cs file like:
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
//whatever you want to pass , write it in yourfnname as a parameter
btnreset.Attributes.Add("onclick", "return YorFnName('test')");
}

ASP.Net LinkButton Prevent Postback Not Working - JavaScript

I know how to prevent javscript within the href attribute from firing as evident in this JSFiddle (http://jsfiddle.net/mkarr/KNefK/)
However, when this logic is applied to an ASP.Net LinkButton as such:
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return formTest.validate(event);" OnClick="btnSubmit_Click"></asp:LinkButton>
which translates to:
<a onclick="return formTest.validate(event);" id="ctl00_m_g_87932399_e546_4e12_8297_982b811d8cea_ctl00_btnSubmit" href="javascript:WebForm_DoPostBackWithOptions('blah blah blah')">Submit</a>
The formTest.validate() method does execute correctly and returns false, but the WebForm_DoPostBackWithOptions is always fired immediately after!
Can anyone see any flaws in my logic that I cannot??
EDIT:
Also, several stack overflow solutions have been accepted for this issue but all of them are doing virtually what I have already done leading me to believe I'm missing something simple!
Disable the postback on an <ASP:LinkButton>
Prevent LinkButton post back OnClientClick not working. Why?
ANSWER:
Since I cannot answer my own question because I'm not reputable yet (LOL), here's an edit with the answer:
Going off #QBM5's original tip of not using ASP.Net controls, I solve the problem, although I still do not know why the initial problem occurred in the first place (does anyone when it comes to ASP.Net? Turn it off, then back on comes to mind here) :o)
I replaced the LinkButton ASP.Net control with the following:
<input type="submit" value="Submit" id="btnSubmitButton" runat="server" OnServerClick="btnSubmitButton_Click" class="submitBtn" />
I then bound the .submitBtn's click event via jQuery:
$('.submitBtn').on('click', function (e) {
if (!instance.validate()) {
e.preventDefault();
}
});
The trick is to use OnServerClick and runat="server" on the control but getting away from LinkButton was the goal and the postback behavior is completely different.
which translates to this:
<input onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(''); " type="submit" id="ctl00_m_g_87932399_e546_4e12_8297_982b811d8cea_ctl00_btnSubmitButton" value="Submit" class="submitBtn">
Anyone want to take a stab at the root cause? I need to move foward so don't have time. :o)
The following is working for me, by changing element.href = "#"
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return ClientSideValidation()" OnClick="btnSubmit_Click"></asp:LinkButton>
Javascript validation
function ClientSideValidation() {
var element = document.getElementById("<%=txtAmount.ClientID%>");
element.href = "";
if (element.value == "") {
element.href = "#";
return false;
}
return true;
}

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?

Javascript alert before a event call not firing

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;" ... />

Enabling Disabling button asp .net - using javascript

Currently in my application I am having a button and a text box. The user types something in the textbox and then presses the button. What I want is that:
The search button should should stay disabled when the page loads for the first time. I can achieve that by setting it to disabled in the code behind file.
Now I want it to remain disabled when the user types upto 2 characters. The moment the user types third character the button should get enabled automatically.
The important thing is that it has to be done without asp .net AJAX since this website will be run from old mobile phones. So only pretty basic javascript or jquery is supported.
Any help will be appreciated.
Thanks
Varun
in order to use the document.getElementById in asp.net and not have to use the full name, you should let asp.net provide it. Instead of:
document.getElementById("ctl00_ctl00_phContent_phPageContent_btnSearch")
Try:
document.getElementById('<%= btnName.ClientID %>')
Where btnName is the asp:Button Id. The <%= code will generate the actual button id, fully qualified, so you don't have to worry about things changing with the hard coded id.
I got this to work with a HTML text box, I don't think you can do it with a asp.net text box:
<head>
<script type="text/javascript">
function TextChange() {
var t = document.getElementById("Text1");
var b = document.getElementById("Button1");
if (t.value.length > 2) {
b.disabled = false;
}
else {
b.disabled = true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" onkeyup="TextChange();" />
<asp:Button ID="Button1" runat="server" Text="Button" Enabled="False" />
</div>
</form>
</body>
If you're using jQuery, use
$(<selector>).val().length
to get the size, then you can set the button's disabled attribute with
$(<button selector>).attr('disabled',false).

Categories

Resources