I need to capture the 'Update' click event with jQuery in an asp.net GridView and have no way of knowing where to start. I'm still rather new to jQuery. My GridView is attached to a SQLDataSource and, naturally, has all the bells and whistles that that combination affords. Any help would be greatly appreciated.
Simply add the script block anywhere after the GridView is declared and it should work with the default non-templated GridView column. No code in the codebehind as it is purely a Javascript solution.
Use this if you are using a Link-type GridView column:
<script type="text/javascript">
// a:contains(The text of the link here)
$('#<%= theGridViewID.ClientID %> a:contains(Update)').click(function () {
alert('Update click event captured from the link!');
// return false: stop the postback from happening
// return true or don't return anything: continue with the postback
});
</script>
Use this if you are using a Button-type GridView column and you don't want your Javascript to block the postback:
<script type="text/javascript">
// :button[value=The text of the button here]
$('#<%= theGridViewID.ClientID %> :button[value=Update]').click(function () {
alert('Update click event captured from the button!');
});
</script>
Use this if you are using a Button-type GridView column and you want to have control whether to continue with the postback or not:
<script type="text/javascript">
// :button[value=The text of the button here]
var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
updateButtons
.attr('onclick', null)
.click(function () {
alert('Update click event captured from the button!');
var doPostBack = true; // decide whether to do postback or not
if (doPostBack) {
var index = updateButtons.index($(this));
// 'Update$' refers to the GridView command name + dollar sign
__doPostBack('<%= theGridViewID.UniqueID %>', 'Update$' + index);
}
});
</script>
Update: I think this would be a better solution in replacement of the last (3rd) script block I presented above, since you won't need to update the __doPostBack function call manually based on the command name, and as such, it should be less error-prone:
<script type="text/javascript">
// :button[value=The text of the button here]
var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
updateButtons.each(function () {
var onclick = $(this).attr('onclick');
$(this).attr('onclick', null).click(function () {
alert('Update click event captured from the button!');
var doPostBack = true; // decide whether to do postback or not
if (doPostBack) {
onclick();
}
});
});
</script>
Credit to Aristos for this idea. :)
Ok here is my solution to capture only one update (or more) from a button.
This is the javascript code that I run on update click
<script type="text/javascript">
function NowRunTheUpdate(){
alert("ok I capture you");
}
</script>
and here is the page code
`<asp:GridView ID="MyGridView" runat="server" OnRowDataBound="MyGridView_RowDataBound" ... >`
<asp:ButtonField Text="update" CommandName="Update" ButtonType="Button" />
...
Here is the code thats run behind and set the javascript.
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// I go to get the button if exist
Button button = control as Button;
if (button != null && button.CommandName == "Update")
// Add delete confirmation
button.OnClientClick = "NowRunTheUpdate();";
}
}
}
}
You need to attach a client-side event listener to the click event of the Update [link]button. I don't think it can be done using AutoGenerateEditButton="true" if you are doing it that way. You'll need to use a TemplateField so that you can manipulate the button. Then you can use jQuery to bind to the click event of the button.
Add the update column to the column templates. Convert it to a custom column, and modify it in such a way you can hook to it with jquery i.e. like adding a css class to it.
Gridview is nothing but a table with a bunch of "tr" and "td". If you understand that concept then it would be easy for you to handle anything at client side. If you have enabled auto everything then it will be a link which would result for Edit, Delete, Update or Cancel (Check View Source). The code given below should capture the update click event:
$("a:contains(Update)").live("click", function() {
//alert("hi"); do what needs to be done
return false;//would not sent the control back to server
});
HTH
Related
I have a Search feature. if the search string is empty and user clicks "GO" then the postback of the gridview shouldn't happen and the alert (as mentioned in below code) should get fired up.
My gridview is in update panel. Below is the logic that i have written but it doesn't works.
protected void btnGo_Click(object sender, EventArgs e)
{
if (!txtSearchString.Text.Equals(string.Empty))
{
BinGrid();
upnl1.update //update panel is updated here.
}
else
{
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Search", "alert('Enter search text');", false);
//upnlgvOpportinities.Update();
//upnlAdmin.Update();
return;
}
}
Please help! Let me know if any info is needed
This logic is wrong. It should do using javascript if you want to avoid the postback at first place.
Have your javascript return false when textbox is empty and true when not
<asp:button runat="server".... OnClientClick="return myfunction(); " />
You can check if textbox is empty or not in myfunction()
Replace Your ScriptManager line with below code line.
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Script", "alert('Enter search text');", true);
If you don't want a request to the server to be sent (if I understood your needs right), than you need a client-side solution, that is handle button click with javascript and conditionally prevent the postback. However your current code is server-side, and is executed on a server after the postback has occurred.
As to client-side, here is one possible way. Define a js function that simply checks the value of the search box and returns false if it is empty. On the button click simply call this function. If a click handler returns false, further processing of the button click will be stopped and the postback won't occur:
function checkSearch() {
var searchBox = document.getElementById('HereComesSearchBoxClientID');
if (searchBox.value == '') {
alert('Enter search text');
return false;
} else {
return true;
}
}
<asp:Button ID="SearchButton" runat="server" Text="GO" OnClick="ServerSideHandler" OnClientClick="checkSearch();" />
#Madhur Ahuja's way is the correct one. Expanding that a little bit more.
HTML
<asp:Button ID="txtSearchString" runat="server"
OnClientClick="javascript:return CheckifEmpty(this);" />
Javascript
function CheckifEmpty(objSearchBox) {
//always trim, otherwise it will accept a string of spaces
var isEmpty = objSearchBox.value.trim() == "";
if (isEmpty) {
alert('Enter search text');
}
return !isEmpty;
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
};
}
Is there a way to change the values for these two attributes on the client side and have it reflected on the server side after the postback. I tried it but it does not seem to work. I wanted to have one button on the page that I would delegate submits too, and assign these two arguments on the client side. Seems like not possible. Any idea?
Assuming there is a button named "cmd" in the form
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#<%=cmd.ClientID %>").click(function () {
$(this).attr("CommandName", "do").attr("CommandArgument", "arg2");
});
});
</script>
If one checks the value after postback they are still the same as they were before postback.
I tried you're code and it works fine.
Just make sure you're button is not generating a postback by adding OnClientClick="return false;":
<asp:Button ID="cmd" runat="server" Text="Button" OnClientClick="return false;"></asp:Button>
Also you won't see the difference in "view source" on your browser. But the change has been made in the DOM. Use firebug and add the console.log to see for yourself:
$("#<%=cmd.ClientID %>").click(function () {
$(this).attr("CommandName", "do").attr("CommandArgument", "arg2");
console.log(this);
});
The console.log(this) gave me the following:
EDIT:
If you think about it. If the button creates a postback, then the button will reset itself to normal once the page loads again.
EDIT #2:
I don't need the change on the client
side, I need it on the server side.
That was the whole point of the
question. I need to see the change on
the server side, and it does not seem
to be possible. – epitka
Okay... Well, in that case. It is not possible. "CommandArgument" and "CommandName" means nothing to the client and is not accessible.
However there are work arounds. But depending on the context of your application they might not be useful to you.
You could try using your own attributes like the answer suggested here.
Or you could execute the __doPostBack on the client side and pick up the __EVENTARGUMENT on the code behind.
(The link button is there to generate the __doPostBack function by asp.net.)
Like such:
<script type="text/javascript" language="javascript">
function DoPostBack() {
__doPostBack('cmd', 'thesearemyarguments');
}
</script>
Page:
<asp:Button ID="cmd" runat="server" Text="Button"
OnClientClick="DoPostBack(); return true;"
onclick="cmd_Click" ></asp:Button>
<asp:LinkButton ID="LinkButton1" runat="server" Visible="false">LinkButton</asp:LinkButton>
Code Behind:
protected void cmd_Click(object sender, EventArgs e)
{
Response.Write(Request.Params["__EVENTARGUMENT"]);
}
I was having the same problem here, I found the solution was to use an ajax call to send my buttons id to a function where i can set it as a session variable. Because the asp control I wanted to update could not be accessed from within a static call. On success of the ajax call I click a hidden button which uses a non static click event to manipulate the session variable i set and update the control
My links were generated within a repeater, and they correspond to different rooms of a house. When you click on the link there is another repeater that has to update to show products that are sold which are relevant to the room of the house that was clicked on
my link that is generated from the repeater
<%#Eval("DocumentName") %>
my client side method
$('.changeroom').each(function () {
$(this).on('click', function () {
var id = $(this).attr('data-id');
var object = { 'sender': id };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/App/Page Templates/FindByRoom.aspx/UpdateRoomID",
data: JSON.stringify(object),
success: function() {
$('#btnID').click();
}
});
});
});
btnID is a simple aspButton with a server side click event
and finally my server side methods
protected void btnChangeRoom_OnClick(object sender, CommandEventArgs e)
{
int id = 0;
if (Session["RoomID"] == null) return;
Int32.TryParse(Session["RoomID"].ToString(), out id);
if (id == 0) return;
//do something with your buttons id
//i updated the path of a repeater and reloaded the data
}
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void UpdateRoomID(string sender)
{
HttpContext.Current.Session["RoomID"] = sender;
}
I am using UpdatePanel ---> LinkButton --> Div --->Table Structure.
When I click the Linkbutton the div has to show the table format first and has to execute the code in its OnClick event, the problem I am facing is I've tried so many jquery functions shown below:
<asp:LinkButton ID="lnkbtnUnitAdd" runat="server" OnClientClick="Toggledivs()" OnClick="lnkbtnAdd_Click" Text="Add" ></asp:LinkButton>
Even if I used:
$(document).ready(function()
{
$("#lnkbtnUnitAdd").click(function () {
$("#divUnit").show("slow"); return false;
});
});
or
function Toggledivs()
{
$("#lnkbtnUnitAdd").click(function () {
$("#divUnit").show("slow"); return false;
});
}
or without using the OnClientClick property in LinkButton
the result is same, as the function is returning false in button Onclient click or document.ready function(), therefore buttons Onclick event is not firing.
And if I comment the return false, the div is not showing up properly.
Please help how to deal as the whole process is running in an updatepanel.
You might have to use Control.ClientID in this case. Try this
$(document).ready(function(){
$("#<%=lnkbtnUnitAdd.ClientID%>").click(function () {
$("#divUnit").show("slow"); return false;
});
});
I won't recommend adding the event handler in HTML. But the following code should work. You don't have to assign the click event again.
function Toggledivs()
{
$("#divUnit").show("slow");
return false;
}
Give
return true;
if you want the onclick function to get executed.
If I have understood what you meant, this should do it:
__doPostBack should be called only after the animation is done, you can do it by passing a callback function to jquery's show's, second parameter.
UPDATES:
$(document).ready(function()
{
$("#lnkbtnUnitAdd").click(function (e) {
var btnName = $(this).attr('name');
$("#divUnit").show("slow",function(){
__doPostBack(btnName,''); //now call the actual postback event
});
e.preventDefault(); //prevent default postback behavior
return false;
});
});
Why doesn't this work?
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.myButton').click();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton id="ttt" runat="server" PostBackUrl="~/Default.aspx" CssClass="myButton">Click</asp:LinkButton>
</div>
</form>
Do you want to submit the form, or add a Click event?
Your link button translates to
<a id="ttt" class="myButton" href="javascript:WebForm_DoPos[...]">Click</a>
, so it has no on-click javascript. Therefore, .click(); does nothing.
I haven't test it, but maybe this will work:
eval($('.myButton').attr('href'));
trigger('click') fires jQuery's click event listener which .NET isn't hooked up to. You can just fire the javascript click event which will go to (or run in this case) what is in the href attribute:
$('.myButton')[0].click();
or
($('.myButton').length ? $('.myButton') : $('<a/>'))[0].click();
If your not sure that the button is going to be present on the page.
Joe
If you need the linkbutton's OnClick server-side event to fire, you need to use __doPostback(eventTarget, eventArgument).
ex:
<asp:LinkButton ID="btnMyButton" runat="Server" OnClick="Button_Click" />
<script type="text/javascript">
function onMyClientClick(){
//do some client side stuff
//'click' the link button, form will post, Button_Click will fire on back-end
//that's two underscores
__doPostBack('<%=btnMyButton.UniqueID%>', ''); //the second parameter is required and superfluous, just use blank
}
</script>
you need to assign an event handler to fire for when the click event is raised
$(document).ready(function() {
$('.myButton', '#form1')
.click(function() {
/*
Your code to run when Click event is raised.
In this case, something like window.location = "http://..."
This can be an anonymous or named function
*/
return false; // This is required as you have set a PostbackUrl
// on the LinkButton which will post the form
// to the specified URL
});
});
I have tested the above with ASP.NET 3.5 and it works as expected.
There is also the OnClientClick attribute on the Linkbutton, which specifies client side script to run when the click event is raised.
Can I ask what you are trying to achieve?
The click event handler has to actually perform an action. Try this:
$(function () {
$('.myButton').click(function () { alert('Hello!'); });
});
you need to give the linkButton a CssClass="myButton" then use this in the top
$(document).ready(function() {
$('.myButton').click(function(){
alert("hello thar");
});
});
That's a tough one. As I understand it, you want to mimic the behavior of clicking the button in javascript code. The problem is that ASP.NET adds some fancy javascript code to the onclick handler.
When manually firing an event in jQuery, only the event code added by jQuery will be executed, not the javascript in the onclick attribute or the href attribute. So the idea is to create a new event handler that will execute the original javascript defined in attributes.
What I'm going to propose hasn't been tested, but I'll give it a shot:
$(document).ready(function() {
// redefine the event
$(".myButton").click(function() {
var href = $(this).attr("href");
if (href.substr(0,10) == "javascript:") {
new Function(href.substr(10)).call(this);
// this will make sure that "this" is
// correctly set when evaluating the javascript
// code
} else {
window.location = href;
}
return false;
});
// this will fire the click:
$(".myButton").click();
});
Just to clarify, only FireFox suffers from this issue. See http://www.devtoolshed.com/content/fix-firefox-click-event-issue. In FireFox, anchor (a) tags have no click() function to allow JavaScript code to directly simulate click events on them. They do allow you to map the click event of the anchor tag, just not to simulate it with the click() function.
Fortunately, ASP.NET puts the JavaScript postback code into the href attribute, where you can get it and run eval on it. (Or just call window.location.href = document.GetElementById('LinkButton1').href;).
Alternatively, you could just call __doPostBack('LinkButton1'); note that 'LinkButton1' should be replaced by the ClientID/UniqueID of the LinkButton to handle naming containers, e.g. UserControls, MasterPages, etc.
Jordan Rieger
The ASP.NET AJAX ModalPopupExtender has OnCancelScript and OnOkScript properties, but it doesn't seem to have an OnShowScript property. I'd like to specify a javascript function to run each time the popup is shown.
In past situations, I set the TargetControlID to a dummy control and provide my own control that first does some JS code and then uses the JS methods to show the popup. But in this case, I am showing the popup from both client and server side code.
Anyone know of a way to do this?
BTW, I needed this because I have a textbox in the modal that I want to make a TinyMCE editor. But the TinyMCE init script doesn't work on invisible textboxes, so I had to find a way to run it at the time the modal was shown
hmmm... I'm pretty sure that there's a shown event for the MPE... this is off the top of my head, but I think you can add an event handler to the shown event on page_load
function pageLoad()
{
var popup = $find('ModalPopupClientID');
popup.add_shown(SetFocus);
}
function SetFocus()
{
$get('TriggerClientId').focus();
}
i'm not sure tho if this will help you with calling it from the server side tho
Here's a simple way to do it in markup:
<ajaxToolkit:ModalPopupExtender
ID="ModalPopupExtender2" runat="server"
TargetControlID="lnk_OpenGame"
PopupControlID="Panel1"
BehaviorID="SilverPracticeBehaviorID" >
<Animations>
<OnShown>
<ScriptAction Script="InitializeGame();" />
</OnShown>
</Animations>
</ajaxToolkit:ModalPopupExtender>
You should use the BehaviorID value mpeBID of your ModalPopupExtender.
function pageLoad() {
$find('mpeBID').add_shown(HideMediaPlayer);
}
function HideMediaPlayer() {
var divMovie = $get('<%=divMovie.ClientID%>');
divMovie.style.display = "none";
}
If you are using a button or hyperlink or something to trigger the popup to show, could you also add an additional handler to the onClick event of the trigger which should still fire the modal popup and run the javascript at the same time?
The ModalPopupExtender modifies the button/hyperlink that you tell it to be the "trigger" element. The onclick script I add triggers before the popup is shown. I want script to fire after the popup is shown.
Also, still leaves me with the problem of when I show the modal from server side.
TinyMCE work on invisible textbox if you hide it with css (display:none;)
You make an "onclick" event on TargetControlID, for init TinyMCE, if you use also an updatepanel
For two modal forms:
var launch = false;
var NameObject = '';
function launchModal(ModalPopupExtender) {
launch = true;
NameObject = ModalPopupExtender;
}
function pageLoad() {
if (launch) {
var ModalObject = $find(NameObject);
ModalObject.show();
ModalObject.add_shown(SetFocus);
}
}
function SetFocus() {
$get('TriggerClientId').focus();
}
Server side: behand
protected void btnNuevo_Click(object sender, EventArgs e)
{
//Para recuperar el formulario modal desde el lado del sercidor
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>launchModal('" + ModalPopupExtender_Factura.ID.ToString() + "');</script>", false);
}
var launch = false;
function launchModal() {
launch = true;
}
function pageLoad() {
if (launch) {
var ModalPedimento = $find('ModalPopupExtender_Pedimento');
ModalPedimento.show();
ModalPedimento.add_shown(SetFocus);
}
}
function SetFocus() {
$get('TriggerClientId').focus();
}