OnClientClick not triggering on first click on button after postback - javascript

I have an ASP button. On click of it I am opening a pop-up after doing some validations using JavaScript.
<asp:Button ID="btnHistory" runat="server" Text="History" Enabled="true" Width="100pt" OnClientClick="ShowHistoryPopup()" meta:resourcekey="btnHistory" OnInit="btnHistory_Init"/>
function ShowHistoryPopup() {
var age = $get("<%= txtSomeTextBox.ClientID %>");
var str = "";
if (Validate(age)) {
str = 'ClService.aspx?id=' + 'Null,' + age.value;
window.open(str);
}
else {
return false;
}
}
I have a radio button. Based on selected index I need to enable disable the History button. Radio button has 3 options and on 3rd option page postback happens. I need to keep the button enable on 1 st option only. I have implemented this logic with the help of Java Script and some code on OnPreRender event(for post back case).
Now the problem I am facing is, if I select option 1 or 2 and click History button, OnClientCLick event is triggering. But if I select option 3(postback) and then navigate back to option 1, onClientCLick is NOT triggering for the very first time. But on clicking the History button 2nd time its working fine. Anyone having suggestions or solution for this problem?

If I understand your problem I think what's happening is you are posting back after the History Button click which isn't what you want (as there's no click handler). Using this code works for me:
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="Radio1" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="Radio1" />
<asp:RadioButton ID="RadioButton3" runat="server" AutoPostBack="True" GroupName="Radio1" />
<asp:Button ID="btnHistory" runat="server" Text="History" Enabled="true" Width="100pt" OnClientClick="ShowHistoryPopup();return false;" meta:resourcekey="btnHistory" />
<script type="text/javascript">
function ShowHistoryPopup() {
alert("Here");
}
</script>
All I've added is the return false; after ShowHistoryPopup();
Also, I've used alert here for the purposes of demo, in reality we should really be using console.log('Show my message');

Related

asp.net Run Javascript confirm from codebehind with custom text and return if OK selected

I have a grid on a page with a list of items - I have a column for tickbox - One use is to remove/delete item.
I have a button "Delete Item" - this runs some code behind to find the item ticked and if only one ticked I would like to ask the user - "Do you want to delete item ABC ... " i.e. showing the text of item selected - If they click OK continue.
I have tried a few options - closest is to use a hidden field to store the value as in below but the code behind goes to the line to read the hidden field before the confirm box comes up so its not going to pick up the value. The confirm box opens OK and message OK.
<script type="text/javascript">
function Confirm(txt) {
if (confirm(txt)) {
hdnResultValue = 1
}
}
</script>
<asp:HiddenField ID="hdnResultValue" Value="0" runat="server" />
<asp:Button ID="DelItem" runat="server" Text="Remove Item"/>
In code behind
Page.ClientScript.RegisterStartupScript(Page.GetType(), "myconfirm", "Confirm('" & txtMsg & "');", True)
If hdnResultValue.Value = 1 Then
'Code to delete
End If
Appreciate any ideas on getting this to work or alternatives.
Reply to Jon:-
Thanks Jon - I had a go at that but doesn't get the itemname - suspect its because I need to reference the grid - presume rather than "this" I need the gridID but this didn't work either.
Below main part of page:-
In console first log for "this" came up empty. I have the button sitting above the grid not as part of the grid!.
<script type="text/javascript">
function confirmClick() {
var itemName;
itemName = $(this).closest("tr").find("td:eq(2)").text();
//AS I haven't tested this lets add some debugging
//Check $(this) exists
console.log($(this));
//Check we got a tr
console.log($(this).closest("tr"));
//Check we got the target td
console.log($(this).closest("tr").find("td:eq(2)"));
return confirm("Are you sure you want to delete: " + itemName);
confirm(txt)
}
</script>
<div>
<asp:Button ID="DelItem" runat="server" Text="Delete Item" OnClientClick="return confirmClick();"/>
</div>
<asp:GridView ID="ItemList" runat="server">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="Select" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ItemID" HeaderText="ItemID" Visible="True">
</asp:BoundField>
<asp:BoundField DataField="ItemName" HeaderText="Item Name" Visible="True">
</asp:BoundField>
</asp:GridView>
The probelm with your approach is that by the time your javascript is triggered the page has already been posted back. So then when the client clicks "OK" the page will have to be posted back yet again.
The rule to remember is javascript is executed client side in the browser, vb.net on the server. Also remember that the whole serverside code is executed before the page (HTML/CSS/javascript) is returned to the browser. So in your current example the hdnResultValue.Value = 1 check is going to happen before the javascript is executed, as the page has yet to be sent to the browser.
What you need to do is trigger the javascript before the page is posted back
<asp:Button ID="DelItem" runat="server" Text="Remove Item" OnClientClick="return confirmClick(this);"/>
Then have your javascript already on the page, I'm going to use the incredibly helpful jQuery library to get the text for the item:
<script type="text/javascript">
function confirmClick(itemClicked) {
var itemName;
//If you have a class on the colum with the item for this example
//class="itemName"
//itemName = $(itemClicked).closest("tr").find(".itemName").text();
//If you don't have a class you could use the columns index
//3rd column for this exampl
//Index is 0 based
itemName = $(itemClicked).closest("tr").find("td:eq(2)").text();
//AS I haven't tested this lets add some debugging
//Check $(this) exists
console.log($(itemClicked));
//Check we got a tr
console.log($(itemClicked).closest("tr"));
//Check we got the target td
console.log($(itemClicked).closest("tr").find("td:eq(2)"));
return confirm("Are you sure you want to delete: " + itemName);
}
</script>
Don't forget to include the jQuery library!
Your other option is yo use AJAX for an asynchronous post back to generate the confirm message.
Here's an article outlining how to use the ModalPopUpExtender to use a fancier confirm: http://mattberseth.com/blog/2007/07/confirm_gridview_deletes_with.html.
Update A quick bug fix. I forgot to pass through the item bein click. It has been added as a parameter to the javascript function.
Demo of the script in action
Update 2 - Get Text of checked row
Change button to (we've taken out the parameter):
<asp:Button ID="DelItem" OnClientClick="return confirmClick();" runat="server" Text="Remove Item" />
Change your script to
function confirmClick() {
//<%= ItemList.ClientId %> gets the rendered client side ID of your gridview
var table = $("<%= ItemList.ClientId %>");
var checkedRow = $(table).find("tr").has("input:checked");
var itemName = $(checkedRow).find("td:eq(2)").text();
return confirm("Are you sure you want to delete: " + itemName);
}
Script Demo
To set value of hidden field do
document.getElementById("hdnResultValue").value = 1;

jqGrid : open a customised form on click of 'Edit' button and after edit refresh that row

I need to open a customized form on click of 'Edit' button which is present on each row of jqGird. Here I know that, I have to open this form on event called 'OnEdit'. To a customized form I will pass information of selected row so that I can edit my information and then I will click on 'Save' button present on my form.
On click of 'Save' button following things should be happened :
1. All modified data will get inserted in database.
2 Selected row should be updated with modified value.
Please tell me how I can do this. Also let me know your suggestions.
Note : I am using ASP .Net MVC website.
Thank You
Basic points:
1) You open/close the gridview and the edit form with Panel
2) You use the OnRowCommand to trigger the edit
3) You have other buttons inside the form to trigger the save/cancel/close
and here is the basic code:
<asp:Panel id="pnlViewList" runat="server">
<asp:GridView ID="gvMyList" OnRowCommand="RowCommand" DataKeyNames="UserId" ..........>
<Columns>
<asp:ButtonField Text="Edit" CommandName="EditMe" />
........rest of your fields.........
</Columns>
</asp:GridView>
</asp:Panel>
<asp:Panel id="pnlEdit" runat="server">
<h2>form edit</h2>
Name : <asp:textbox id="txtName" runat="server" />
........rest of your form.........
</asp:Panel>
and on code behind you capture the edit from the grid view.
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditMe")
{
int iTheIndexNow;
if (int.TryParse(e.CommandArgument.ToString(), out iTheIndexNow))
{
gvMyList.SelectedIndex = iTheIndexNow;
// close the gridview, open the form
pnlEdit.Visible = true;
pnlViewList.Visible = false;
// load the form for editing
LoadLineForEditing(gvMyList.SelectedValue.ToString());
}
}
}

css class applying after double-click on the asp.net button

i want to apply a class on a asp.net label when validation fails, everything is working fine but it is requiring double-click to apply the class. First click to show the error message of the required field validator and second click applies the class. I need it in one click. Please help
<script>
function Validate()
{
//for textbox
if ($('#<% =RequiredFieldValidator1.ClientID %>').css('visibility') == 'visible')
{
$('#<% =Label1.ClientID %>').addClass('error');
}
else
{
$('#<% =Label1.ClientID %>').removeClass('error');
}
}
</script>
<asp:Label ID="Label1" runat="server" CssClass="lbl" Text="Name"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" OnClientClick="Validate()"
Text="Submit" ValidationGroup="txt" />
You need to call your Validate() function directly on the page load.
The code is currently doing exactly what you asked it to do, when the validator is visible(after first click), and button is clicked, change color.
Add code like this to call the function onload
window.onload = Validate();

asp:Button in jQuery dialog box not firing OnClick event

I have an asp:Button inside a jQuery dialog for which the OnClick event isn't firing. I'm using the PostBackUrl property to navigate to another page, but I want to set this property in the OnClick event so that I can append a query string variable according to the name of a file they upload in the dialog. I posted a question about this dialog earlier, because I couldn't get it to post back at all, but that's been fixed. Clicking the button posts back fine, and I can set the PostBackUrl property in the asp markup, or in the Page_Load() of the code behind. But I can't get the OnClick function to fire for some reason, and that's where I want to set the PostBackUrl. Here's the .aspx...
<form id="frmDialog" runat="server">
<asp:Button ID="btnDisplayDialog" runat="server" Text="Click to Display Login Dialog" OnClientClick="showDialog(); return false;" />
<div class="divInnerForm"></div>
<div class="divDialog" style="display: none">
<table style="width: 100%;">
<tr>
<td>First Name: <asp:TextBox ID="txtFirstName" runat="server" Text=""></asp:TextBox></td>
<td>Last Name: <asp:TextBox ID="txtLastName" runat="server" Text=""></asp:TextBox></td>
</tr>
<tr>
<td>
How Old are You?
<asp:DropDownList ID="ddlAge" runat="server">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:DropDownList>
</td>
<td>
How Many Siblings do You Have?
<asp:DropDownList ID="ddlNumberSiblings" runat="server">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
What is your birthday?
<input type="text" id="datepicker" name="datepicker" />
</td>
</tr>
<tr>
<td>
Please Choose a Picture to Upload:
<asp:FileUpload ID="fupUserPicture" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnUserPicture_Click" />
</td>
</tr>
</table>
</div>
</form>
...the jQuery script that displays the dialog and places it within the form...
function showDialog() {
$('.divDialog').dialog({
modal: true, show: 'slide', width: 500,
open: function (event, ui) {
$('.divInnerForm').append($(this).parent());
}
});
}
...and the code behind with my OnClick function....
protected void btnUserPicture_Click(object sender, EventArgs e)
{
string fileName = "";
if (fupUserPicture.HasFile)
{
try
{
fileName = Path.GetFileName(fupUserPicture.FileName);
fupUserPicture.SaveAs(Server.MapPath("~/Images/" + fileName));
}
catch (Exception ex)
{
}
btnSubmit.PostBackUrl = "~/Profile.aspx?pic=" + fileName;
}
}
EDIT: Ok, here's how the submit button in the dialog actually renders as HTML. I think this may be the problem. As you can see, the javascript onclick simply provides "Profile.aspx" as the post back url, even though it seems to me any server side code should execute first and foremost. This is within the form...
<input id="btnSubmit" type="submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("btnSubmit", "", false, "", "Profile.aspx", false, false))" value="Submit" name="btnSubmit">
..and here's how it renderes if I remove btnSubmit.PostBackUrl = "~/Profile.aspx" from the Page_Load() function....
<input id="btnSubmit" type="submit" value="Submit" name="btnSubmit">
EDIT 2: ok so I've added another hidden asp button outside of the dialog, and the button inside the dialog now calls a javascript function which triggers the OnClick event of the hidden button. Same thing, the javascript function runs fine, but btnHidden_Click() function does not run! I'm at a total loss, at this point I literally have no idea why this isn't working. Here's the new Hidden Button, outside of the dialog div but inside of the form as you can see....
</div>
<asp:Button ID="btnHidden" runat="server" Text="" Visible="false" ClientIDMode="Predictable" OnClick="btnHidden_Click"/>
</form>
...here's the button inside the dialog with the OnClientClick event, which as I've said runs fine...
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="forcebtnHiddenClick(); return false;" />
And here's the OnClick function in the code behind for btnHidden, though it's exactly the same as before...
protected void btnHidden_Click(object sender, EventArgs e)
{
string fileName = "";
if (fupUserPicture.HasFile)
{
try
{
fileName = Path.GetFileName(fupUserPicture.FileName);
fupUserPicture.SaveAs(Server.MapPath("~/Images/" + fileName));
}
catch (Exception ex)
{
}
Response.Redirect("~/Profile.aspx?pic=" + fileName);
}
}
...and the javascript function that runs, but for some reason doesn't result in btnHidden_Click running...
function forcebtnHiddenClick(e) {
//__doPostBack('btnHidden', 'OnClick');
$('#btnHidden').trigger('click');
}
..as you can see I've tried both .trigger('click') and __doPostBack(), both to no avail.
EDIT: Ok, so the problem is definitely the
function forcebtnHiddenClick() {
__doPostBack('btnHidden', '');
}
function, which is not actually triggering the btnHidden_Click event. When I make btnHidden visible and click it directly, the btnHidden_Click function runs fine.
EDIT: After TONS of searching, found this and got it to work...
function forcebtnHiddenClick() {
<%= ClientScript.GetPostBackEventReference(btnHidden, string.Empty) %>;
}
I don't know why
__doPostBack(<%= btnHidden.ClientID %>, '')
doesn't work.
Try this
function showDialog() {
$('.divDialog').dialog({
modal: true, show: 'slide', width: 500
});
$(".divDialog").parent().appendTo($("form:first"));
}
You should be appending divDialog to the form not that empty divInnerForm.Then your button will be in the form and its on click event will fire happily.
Update
Try also using onclient click.Then wire this attribute to a function which will force a post back on the hidden button.
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="forceClick();" />
<asp Button id="hidButton" runat="server" onclick="hidButton_Click" />
function forceClick(){
__doPostBack('<%#hidButton.UniqueId %>');
}
Then use the event handler hidButton_Click to put your code.
$(this).parent().appendTo('form')
should work fine.. Append it to the form to fire server side events
When I use the jQuery dialog, I always use the buttons that come as part of the dialog. Then when they're clicked, I call a javascript function to perform my action.
If I need to handle a PostBack from those buttons, then I create a separate ASP.Net button on the page - this is the button I use to handle my OnClick event. The user won't click this ASP.Net button, though (I hide it with css so it's not visible on the page). Instead, the javascript function I call when they click the dialog button will call code that will mimic a click of my ASP.Net button.
The result is that when the dialog button is clicked, the page will PostBack as though the ASP.Net button was clicked, and I can handle it via my OnClick event.
Here's some sample code (in VB.Net)...
Dim csm As ClientScriptManager = Page.ClientScript
Dim js As New StringBuilder
js.AppendLine("function handleSubmitMyButton() {")
js.AppendLine(csm.GetPostBackEventReference(MyButton, ""))
js.AppendLine("}")
csm.RegisterClientScriptBlock(Me.Page.GetType, "create_call_to_MyButton", js.ToString, True)
When the page is built, it will include the handleSubmitMyButton() javascript function. The dialog button click will call this function, which will trigger the PostBack as though the 'MyButton' button was clicked.
Usually I don't have to hide the ASP.Net button with css. It's often the button that gets clicked to open the dialog. I prevent the PostBack when it opens the dialog; then when the dialog button is clicked, I mimic the click of that button.
UPDATE:
I saw several people mention the following line of code
$(this).parent().appendTo(jQuery("form:first"));
I thought that's what you were attempting to do with your line of code:
$('.divInnerForm').append($(this).parent());
If that doesn't do the same thing, though, you would need to have the code to add your fields to the form.
I use the modal dialog and i need to add a row, otherwise i get the modal transparency over the close button!
var $ObjDialog = $("div[id*='div_MyPopup']");
$ObjDialog.dialog({
modal: true
});
$ObjDialog.parent().prev().appendTo($("form:first"));
$ObjDialog.parent().appendTo($("form:first"));

ASP.Net Ajax Control Toolkit "UpdatePanelAnimationExtender" breaking jQuery focus() onload

I have the following update panel with a text field limited to 9 characters only accepting numbers.
<asp:UpdatePanel ID="updatePanelsearchusers" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="formfieldarea">
<div id="searchfield1" class="searchfieldbox">
<asp:Label ID="USIDSearchlbl" runat="server" Text="USID: " CssClass="formlabel" />
<asp:TextBox ID="USIDSearchBox" runat="server" MaxLength="9" />
<cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server" TargetControlID="USIDSearchBox" ValidChars="0123456789" />
<asp:ImageButton ID="USIDsearchbutton" runat="server" ImageUrl="/tissuebank/images/searchButton.png" CausesValidation="true" OnClick="search1_Click" CssClass="searchbutton" />
</div>
</div>
<div>{output from search}</div>
</ContentTemplate>
</asp:UpdatePanel>
And the following JavaScript which will automatically trigger the search button if the number of characters reaches 9.
<script type="text/javascript" language="javascript">
function setupUSIDFocus() {
$('#<%=USIDSearchBox.ClientID %>').focus().keyup(function () {
if ($(this).val().length == 9) {
$('.searchbutton').first().click();
}
});
}
$(document).ready(function () { setupUSIDFocus(); });
</script>
If I have the code as above this works fine and loads with the focus being on the element USIDSearchBox as I intended, however when the update panel is updated but the event is no longer assigned to the box and the focus is lost. To fix this I added an ASP.Net Ajax control UpdatePanelAnimationExtender so that the focus and events are reassigned when the request is complete.
<AjaxControlToolkit:UpdatePanelAnimationExtender ID="upae" runat="server" TargetControlID="updatePanelsearchusers">
<Animations>
<OnUpdated>
<Sequence>
<Parallel duration="0">
<ScriptAction Script="setupUSIDFocus();" />
</Parallel>
</Sequence>
</OnUpdated>
</Animations>
</AjaxControlToolkit:UpdatePanelAnimationExtender>
And indeed this does reset the focus and the keyup event but for some reason the element does not get focus when the page is first loaded. Though the keyup event is still attached onload I am just missing the focus being on the USIDSearchBox field. If I remove the UpdatePanelAnimationExtender then I get the focus back on load, so it must be something to do with this control.
Does anyone have any idea how to get the focus onload of the page?
Alternatively, you can use 'ScriptManager.RegisterStartupScript' in 'search1_Click' to call the jQuery function after ajax update:
ScriptManager.RegisterStartupScript(this,this.GetType(),"myscript","setupUSIDFocus();",true);

Categories