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;
});
});
Related
I'd like to post back to the server when my combobox changes value (ideally with an AJAX call in an update panel - but one thing at a time). I'm using the I'm using the jQuery UI AutoComplete Combobox and, unfortunately, it's interferring with the change event as I'm not changing the drop down list directly.
I'm using the implementation detailed here.
Here are some choice snippets
HTML Body Code
<span class="ui-widget">
<asp:DropDownList ID="cboLang" runat="server" AutoPostBack="True">
<asp:ListItem Value="ActionScript">ActionScript</asp:ListItem>
<asp:ListItem Value="AppleScript">AppleScript</asp:ListItem>
<asp:ListItem Value="Asp">Asp</asp:ListItem>
</asp:DropDownList>
</span>
Autocomplete Javascript
This is the autocomplete js that exexutes whenever a selection has been made. It will always run the function _removeIfInvalid
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
Server Side Code
Protected Sub cboLang_SelectedIndexChanged(sender As Object, e As EventArgs) _
Handles cboLang.SelectedIndexChanged
'DO OTHER STUFF HERE
Dim alert = String.Format("alert('{0}');", "Hi")
ScriptManager.RegisterStartupScript(Me, Me.GetType, "DropDownChange", alert, True)
End Sub
Generated Code
When an ASP.NET renders the page with the attached event, it produces the following code
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['ctl00'];
if (!theForm) {
theForm = document.ctl00;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<select id="cboLang" onchange="javascript:setTimeout('__doPostBack(\'cboLang\',\'\')', 0)"
name="cboLang" style="display: none;">
Question
Where can I go about making changes to ensure that with each update to the autcomplete input, I can trigger a server event?
There are a couple things that are helpful for answering this question. One is to take a look at JQuery-UI's own documentation on this function:
// Initialize the autocomplete with the select callback specified:
$( ".selector" ).autocomplete({ select: function( event, ui ) {}});
// Bind an event listener to the autocompleteselect event:
$( ".selector" ).on( "autocompleteselect", function( event, ui ) {} );
Essentially, what needs to happen, is something needs to signal a callback when the item has been selected (either from the menu or by typing and getting an exact match).
We can do this by modifying the default functionality demonstrated on the autocomplete page:
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
This code attaches listeneres on the select and change events and runs the inline defined function and the _removeIfInvalid function whenever those events fire (respectively)
By implementing the following changes we can do a postback when a valid selection has been made:
//attach listeners
this._on(this.input, {
autocompleteselect: "_selectFromMenu",
autocompletechange: "_removeIfInvalid"
});
Will get called anytime an item is selected from the menu:
_selectFromMenu: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('', '');
},
Will get called any time the text changes:
_removeIfInvalid: function (event, ui) {
// Selected an item, automatically valid, post back
if (ui.item) {
__doPostBack('', '');
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, post back
if (valid) {
__doPostBack('', '');
return;
}
// Remove invalid value...
Here's a jsfiddle with the complete code changes, although __doPostBack is commented out because it is not being handled by anything
A couple further note:
I'm calling __doPostBack, but I'm relying on that method being available because of asp.net event handling generated code.
In order to initialize the combo box, you have to call $("#combobox").combobox();. Make sure that whatever is preforming that operation is still getting called on the return from the post back, otherwise the functionality will not come back. This is one thing to work past if you're using the code asynchronously in an update panel.
Instead of __doPostBack(this.element.attr('name'), '');
write
if (this.element.attr('onchange') != undefined && this.element.attr('onchange').indexOf("__doPostBack") >= 0)
__doPostBack(this.element.attr('name'), '');
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
I have the following javascript:
<script type="text/javascript">
function showjQueryDialog() {
$("#dialog").dialog("open");
}
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: { "Renew Membership": function() { $(this).dialog("close"); } }
});
});
</script>
I have an asp:Button on the page which logs the user it. This is the sample of what I want to occur when the button is clicked on the server-side:
protected void LoginButton_OnClick(object sender, EventArgs e)
{
UserProfile profile = UserProfile.GetUserProfile(txtUserName.Text);
TimeSpan ts = profile.Expiration.Subtract(DateTime.Now);
if(ts.Days <= 30)
//call showJQueryDialog() to open the dialog box
Page.ClientScript.RegisterStartupScript(typeof(Login2), "showjquery",
"showJQueryDialog();", true);
else
//log the user in as normal.
}
Also is how would I attach a method such as the following to the Renew Button on the Dialog
public void Renew()
{
Response.Redirect("Renew.aspx");
}
As calling client side function is not possible I would suggest to emit in javascript the information required for the decision and make everything happen on the client side.
Alternatively you can do need a page reload, as suggested from previous commenter.
if(ts.Days <= 30)
ScriptManager.RegisterStartupScript(
typeof(MyPage), "showjquery",
"$(document).ready(function() { showJQueryDialog(); };",
true
)
else
//log the user in as normal.
Put that right where you have: //call showJQueryDialog() to open the dialog box
Update 1: You seem to be using an update panel, in that case you need to use ScriptManager.RegisterStartupScript
Update 2: You also want to wrap the js call in a jquery .ready call, so it isn't triggered before the dialog has been configured. This is better than hooking up the body onload because onload waits for images to be loaded so .ready will show sooner (depending on the images and other bits of info loaded).
I really don't understand Freddy's approach to this at all. I am misunderstanding something maybe. The way I see it, there are only two possibilities here, as devdimi point out. Either:
a) Do all the logic in the client-side onClick javascript. You could call an AJAX method that performs the action in the server-side OnClick, then call your jQuery popup in the AJAX callback.
b) Do a postback, handle the server-side OnClick, then attach javascript for the page that runs in the body onLoad event:
body.Attributes.Add("onLoad", "showJQueryDialog();")
I would keep a hidden LinkButton and then call the __doPostBack method in javascript.
<asp:LinkButton runat="server" ID="Renew" OnClick="Renew_Click" style="display:none" />
jQuery
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: { "Renew Membership": function() {
$(this).dialog("close");
__doPostBack('Renew', '');
// or if inside a master page something like this
__doPostBack('ctl00$ContentPlaceHolder1$Renew', '');
} }
});
});
I have a somewhat similar issue with IE8.
We're using ASP.NET and anytime we do a Response.Redirect within the PageLoad/Control-Events IE8 sets all the base DOM objects to undefined (Image, window, document)
But if we do the redirect during the PreInit event then IE8 is fine.. Lovely
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();
}