Button Click using JQuery and C# - c#

I need to know if asp control (Button) is clicked or not using jQuery. This is button coding.
How can I pop up an alert box if someone hit a button using jQuery.
<asp:Button ID="delete_checked_box_button_id" OnClick="deletechecked_box_onclick" runat="server" Text="Delete Checked" />
Thanks in advance.

When you set the ClientIDMode property to Static you can use the Id you set:
$(document).ready(function() {
$('#delete_checked_box_button_id').on('click', function(e) {
alert('Button clicked');
});
}

$('#<%=delete_checked_box_button_id.ClientID %>').click(function() {
alert("Handler for .click() called.");
});

You don't need jQuery, you can use the button's property onClientClick
See this example in MSDN

<script type="text/javascript">
function BuyG2() {
alert('Hai Jquery');
}
</script>//jquery in sourse
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>BuyG2();</script>", false);
}//ASP Button Click Event

Related

How to use a button to populate data without doing a postback

I have the following ASP.net button inside my GridView:
<asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnCommand="btnShow_Command" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' />
The code-behind is:
protected void btnShow_Command(object sender, CommandEventArgs e)
{
int index = 0;
if (e.CommandName == "ViewAll")
{
index = Convert.ToInt32(e.CommandArgument);
DataTable cacheTable = HttpContext.Current.Cache["ResultsTable"] as DataTable;
string column = cacheTable.Rows[index].Field<string>("Guideline");
string test = BookingResults.Rows[index].Cells[7].Text;
string html = HttpUtility.HtmlDecode(column);
ResultsDiv.InnerHtml = html;
}
}
The ResultsDiv is shown in a popup using the JQuery:
//CONTROLLING EVENTS IN jQuery
$(document).ready(function () {
//Click the button event!
$(".btnSearch").click(function (e) {
alert($(this).val() + " Clicked");
e.preventDefault();
//centering with css
centerPopup();
//load popup
loadPopup();
});
});
When I navigate to the page, the generated HTML looks as follow (there are multiple rows with the same button in the column):
<input type="button" name="ctl00$ctl33$g_36ed1b14_1f08_43fb_8099_eb3423a33ed9$BookingResults$ctl224$btnShow" value="View All" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl33$g_36ed1b14_1f08_43fb_8099_eb3423a33ed9$BookingResults$ctl224$btnShow", "", true, "", "", false, true))" id="ctl00_ctl33_g_36ed1b14_1f08_43fb_8099_eb3423a33ed9_BookingResults_ctl224_btnShow" class="btnSearch" />
What is happening now, is when I click the View All button it displays the alert, when I click OK, it displays the popup for a split second and refreshes the page.
How can I modify the code-behind/JQuery so that I can click on any of the button, and it will display the alert and show the popup every time and not do a postback?
I think the first thing you need to do even before alert is e.preventDefault();
//CONTROLLING EVENTS IN jQuery
$(document).ready(function () {
//Click the button event!
$(".btnSearch").click(function (e) {
e.preventDefault();
e.stopproPagation();
alert($(this).val() + " Clicked");
//centering with css
centerPopup();
//load popup
loadPopup();
});
});
As what i think that the alert lets the event do its default job first.

Hide tab header on ajax:TabContainer

Based upon my condition I only want to remove tabheader from ajax:TabContainer on button click.
My function is:
<script type="text/javascript">
//<![CDATA[
function hideheadertab() {
$('.ajax__tab_header').hide();
}
//]]>
</script>
And in button click I call function like this.
protected void btnAdd_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>hideheadertab();</script>", true);
}
but no luck.Any trick to do this.Thanks for help.
Note: I want to remove only tab header not whole tab.
tab header html part.
<div id="ctl16_TabContainerManagePortal_header" class="ajax__tab_header">
<span id="ctl16_TabContainerManagePortal_TabPanelPortalAddEdit_tab" class="ajax__tab_active"><span class="ajax__tab_outer"><span class="ajax__tab_inner"><span id="__tab_ctl16_TabContainerManagePortal_TabPanelPortalAddEdit" class="ajax__tab_tab">
<span id="ctl16_TabContainerManagePortal_TabPanelPortalAddEdit_lblAEP">Some Text</span>
</span></span></span></span>
</div>

How to call javascript on user control

I have webapplication in c# asp.net 4.0
I have User Control in that I have written javascript :-
<script>
function SetValue() {
alert(document.getElementById('offSetClient').value);
}
</script>
<asp:HiddenField ID="clientDateTime" runat="server" />
<asp:HiddenField ID="offSetClient" runat="server" Value="Test"/>
and this User Control added into a web form.
Please suggest me how can I call this javascript on User Control page load.
You can use Page.ClientScript.RegisterStartupScript to attain this.
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(GetType(), "ShowAlert", "SetValue('" + offSetClient.ClientID + "');", true);
}
Please add an input parameter for the function to get the object of hidden field and pass the same from function.
<script type="text/javascript">
function SetValue(objHdn) {
alert(document.getElementById(objHdn).value);
}
</script>

OnClick and OnClientClick

I have an image button on a pop up page which is opened by another page
<asp:ImageButton
ID="Button_kalem_islemikaydet"
runat="server"
CausesValidation="False"
ImageUrl="~/images/butonlar/buyuk/Kaydet.jpg"
meta:resourcekey="Button_kalem_islemikaydetResource1"
OnClick="Button_ust_islemikaydet_Click"
OnClientClick="f2()"
Width="100" />
f2() is
<script type="text/javascript">
function f2() {
opener.document.getElementById("TextBox1").value = "hello world";
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.location.href = window.opener.location.href;
}
</script>
And Button_ust_islemikaydet_Click is another method implemented in aspx.cs file and it updates the database tables which are shown in the parent page in a GridView.
What I am trying to do is to doPostBack I mean refresh the opener(parent) page.And with these above codes refresh is working.However, parent page still shows the same data before the refresh.And the reason is that OnClientClick works before OnClick method
So my question is that is there any way I can run the method on OnClick and finish it and then run the OnClientClick method?
<form id="aspnetForm" runat="server">
<asp:Button Text="Click Me" ID="ClickMeButton" OnClick="ClickMeButton_OnClick" runat="server" />
<asp:HiddenField runat="server" ID="UpdateOpenerHiddenField" Value="false" />
<script type="text/javascript">
//1st approach
var updateOpenerField = window.document.getElementById("<%= UpdateOpenerHiddenField.ClientID %>");
if (updateOpenerField.value === "true") {
f2();
updateOpenerField.value = "false";
}
// for the 2nd approach just do nothing
function f2() {
alert("Hello, opener!");
}
</script>
</form>
protected void ClickMeButton_OnClick(object sender, EventArgs e)
{
//1st approach
UpdateOpenerHiddenField.Value = "true";
// 2nd approach
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2();", true);
}
No, you can't run server side code (OnClick event handler) before client side. OnCLientClick event was added to perform some validation before post back. There is only one way to do it - update the f2 method and post data on server via ajax
You can put your javascript inside a PlaceHolder tag which you make visible in your server-side OnClick handler.
aspx code:
<asp:PlaceHolder id="refreshScript" visible="false" runat="server">
window.opener.location.href = window.opener.location.href;
window.close();
</asp:PlaceHolder
cs code:
protected void button_Click(Object sender, EventArgs e) {
// do whatever
refreshScript.Visible = true;
}

A way to store div id as string and send it to button click event via javascript

Is there a way I can send my div id to my asp delete button?
div.ID = String.Format("{0}", reader.GetString(0));
div.Attributes.Add("onclick", "return clickTheButton();");
protected void btnDelete_Click(object sender, EventArgs e)
{
//serverside code if confirm was pressed.
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
{
cmd.ExecuteNonQuery();
}
}
// //PopulateWallPosts();
}
}
ASP:
<script type="text/javascript">
function confirm_delete()
{
return confirm("Are you sure you want to delete this comment?");
}
function clickTheButton() {
document.getElementById('<%= btn.ClientID %>').click();
}
</script>
<p>
<asp:Button ID="btn" OnClientClick="return confirm_delete();" OnClick="btnDelete_Click" runat="server" Text="delete"/>
I need to find a way I can send the div id to the button delete so I can use my sql syntax, atm I cant see a way of how to send it.
You want to use window.event.srcElement.id like this:
function clickTheButton() {
var Sender = window.event.srcElement;
alert("the item clicked was " + Sender.id)
}
for a button that looks like:
<input type="button" id="myButton" onclick="clickTheButton();" value="Click Me"/>
you will get an alert that reads: "the item clicked was myButton.
Are you talking about a situation where you have a number of "delete" buttons, e.g. one for each comment, all hooked up to the same btnDelete_Click() event handler?
You can put a CommandArgument on the Button, e.g.:
<asp:Button ID="btn" OnClientClick="return confirm_delete();" OnClick="btnDelete_Click" runat="server" Text="delete" CommandArgument="123" />
And then pick this up in the event handler like so:
protected void btnDelete_Click(object sender, EventArgs e)
{
string id = ((Button)sender).CommandArgument;
}
Another approach would be to change your ASP button to a HTML button. Wire up an onclick event to the HTML button, and then call javascript function that then hits the server side Web Method.
You may want to re-approach your design, why is the div being selected causing a delete action.
If you want the reference to the actual element, not just its id, you can define your div as:
<div id="myDiv" onClick="btnClickHandler(this)">
...
</div>
This will pass the actual div element into your javascript function btnClickHandler:
<script type="text/javascript">
function btnClickHandler(myDiv)
{
// do stuff with the div here
}
</script>

Categories