Value of Hiddenfield not found in javascript function - javascript

I have spent the couple days researching my issue and have not been able to get it to work correctly. I know there are a few topics here that are related to this issue and reading them has helped me but I'm at a bit of a roadblock and would appreciate a push in the right direction.
I wrote a small .NET 3.5 VB.NET web application that allows users to maintain some data. It consists of 3 pages. One requirement I was not completely fond of was that the user wanted to make all of her changes then hit a save button at the end instead of saving back to the DB each time she applied her changes to the grid.
I'm using an session object to store a collection of objects on each page and want to prompt the user with a dialog if they attempt to change the value of a dropdown or leave the page when there are pending actions. After a lot of research here and in other places, I decided to create a hidden field on the page and update its value each time the action collection is updated on the server side. Then I want to evaluate that value and if it's greater than 0, I want to prompt the user to save changes.
My function:
<telerik:RadCodeBlock ID="RadCodeBlock2" runat="server">
<script type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
var actionCount = $get('<%=ActionCounterField.ClientID %>').value;
if (actionCount > 0) {
alert("Pending Changes!");
}
}
</script>
</telerik:RadCodeBlock>
My hidden field declaration:
<asp:HiddenField id="ActionCounterField" runat="server" />
My server side code:
Protected Sub UpdateActionCount()
ActionCounterField.Value = GoalCategoryActionList.Count
End Sub
When I debug the application and add a record to my grid, the server side code is executed correctly. I have also verified that the hidden control is found by the javascript function. What I haven't been able to figure out, though, is why the hidden field value is not found by the function.
Any help is greatly appreciated. Thank you!

OK, I figured out how to do this. I won't claim it's the most elegant solution but it works exactly how I want it to work so I'm happy. Thank you for the responses. I appreciate the help.
First, I changed the hidden field to a telerik RadTextBox and set it up to not display. The RadTextBox just appears to play better with the RadGrid than the hiddenfield was.
<telerik:RadTextBox id="ActionCounterField" runat="server" style="display: none;" AutoPostBack="true" />
Then I wired it up in the AjaxManager to be changed by my RadGrid.
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadGrid1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="ActionCounterField"></telerik:AjaxUpdatedControl>
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
I conditionally call the confirmation function. When my user hits the save or undo button, the changes are persisted to the DB or undone without confirmation. If they attempt to leave the page in any other way, however, they are prompted to save their changes. If they hit "OK" the save button handler is called on the server side. If they hit "Cancel", the undo button handler is called.
var allowConfirm = true
window.onbeforeunload = confirmExit;
function confirmExit()
{
var actionCountHolder = document.getElementById("<%=ActionCounterField.ClientID %>");
var actionCount = actionCountHolder.value;
if (allowConfirm == true)
{
if (actionCount > 0)
{
var conf = confirm("You have pending changes. Save them?");
if (conf == true)
{
var saveButton = document.getElementById("<%=btnSave.ClientID %>");
saveButton.click()
}
else
{
var cancelButton = document.getElementById("<%=btnCancel.ClientID %>");
cancelButton.click();
}
}
}
else {
allowConfirm = true;
}
}
Also, I have the save and undo buttons calling the disableConfirm function on their OnClientClick action.
<asp:Button ID="btnSave" OnClick="btnSave_Click" OnClientClick="disableConfirm()" runat="server" Text="Apply" />
<asp:Button ID="btnCancel" OnClick="btnUndo_Click" OnClientClick="disableConfirm()" runat="server" Text="Undo" />

Related

issues with parent page postback after closing child modal form

I'm working on an ASP.NET application and I ran into an issue that I am unable to resolve. I have a parent form, called Form1.aspx which contains a Telerik RadGrid. On page load, this grid is completely empty. The user has the ability to add data, by clicking add, in this case a Rad Window opens: here's my code:
<td >
<input id="btnAdd" runat="server" onclick="showQuestion4()"
type="button" value="Add" />
</td>
I have my RadWindowManager like this:
<telerik:RadWindowManager ID="RequestsRadWindowManager" runat="server" >
<Windows>
<telerik:RadWindow ID="ClientQuestion4" runat="server" Behaviors="Close,Move"
EnableEmbeddedSkins="false" Height="300px" Modal="true" OnClientClose="OnClientClose"
ReloadOnShow="true" Skin="WebBlue" Width="550px">
</telerik:RadWindow>
</Windows>
</telerik:RadWindowManager>
And My JS function to actually open the window:
function showQuestion4() {
return window.radopen("mdClientQ4.aspx?mode=add", "ClientQuestion4", "return false;");
return false;
}
My child form opens correctly, and allows user to enter and SAVE data. Once user clicks SAVE, I do an insert and then call this:
RadAjaxManager1.ResponseScripts.Add("cancelAndClose();")
Which corresponds to this JS code:
function cancelAndClose() {
var oWnd = GetRadWindow();
oWnd.close();
}
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
elseif(window.frameElement.radWindow)oWindow=window.frameElement.radWindow;
return oWindow;
}
So this code gets called, my child form Closes successfully, and now the focus returns to my Parent form which has been open in the background.
What's happening here is, I have a Full Page Post back on the parent form, and my main goal is to PREVENT IT.
My RadGrid is currently in Update Panel, with mode="conditional". The trigger for this Update Panel is a dropdown, which enabled the ADD button , which in turns allows the user to open the child form and enter data.
I have been trying to disable this postback for hours to no avail, I have no idea what it is I'm doing wrong.
I set return false; in my showQuestion4() Javascript function, but this still gets bypasses, and the parent page has full page load.
My goal for this, is to close the child form, and NOT have the POST BACK occur in my parent form, rather I want to simply reload the UpdatePanel with RadGrid which would display the information the user entered in the Child form.
Any help or tips will be greatly appreciated. I'd be more than happy to show more code if necessary.
EDIT:
Per Nikkis comment below, I removed runat="server" from btnAdd however, my parent form still goes through postback
Posting as an answer, since it looks like you worked it out from our comment conversation.
Check the UpdatePanel, and be sure any code called on client close is firing as you mean it to fire.

Stop page reload of an ASP.NET button

NET application, I have inserted a button that call a Javascript function (OnClientClick event) and a VB.NET function (OnClick event)
<asp:Button OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
The problem is that when I click the button, it refreshes the page and delete the content of the text boxes.
I have tried with inserting return false; on the OnClienClick event, but it doesn't execute the OnClick Event.
How can I avoid the page reload ?
P.S.: At the end of the Javascript function a new window is opened window.open(newWindow.aspx), but I want that the first page mantain the value inserted by the user in the Text Boxes.
Thanks in advance :)
You need to use return statement at two points.
OnClientClick="return jsfunction();"
function jsfunction()
{
//
return false;
}
OR, you can return false after the function call like this.
OnClientClick="jsfunction(); return false;"
Note if you want to do postback conditionally then you need to return true or false.
OnClientClick="return jsfunction();"
function jsfunction()
{
if(conditionForPostBack)
return true;
else
return false;
}
or you can disable the submit behaviour. By default asp.net renders button as submit button. if you disable submit behaviour it will render button as button type
<asp:Button UseSubmitBehavior="false" OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
But with this code it will not fire server side event "OnClick"
if you are not going to trigger the button with C# Codebehind function, then you dont need to use asp:Button. Therefore you can use a regular html .
<button id='btn_1' onclick='ajax_function()'>Button</button>
html button is much easier and faster. if you use asp:button, then you should use clientid() function to catch the control to trigger the ajax.
Searching for the same thing as you i find a patch:
If you call a method server side, you can use AJAX with the update panel, but that didn't worked for me. But you can save what you want in Session, so you have it as far as Session lasts.
// Save at SessionParameter the elementToSave we want.
this.Session["SessionParameter"] = elementToSave;
// Retrieve the info from the Session
ElementYouNeededToSave = (TypeOfTheElement)Session["SessionParameter"];
Hope this will help someone in my situation.

To give a confirm pop up box within event for submit button and allow or not allow to submit

I have submit button. On its click I have to check a paricular field's value from database and then give a pop up for confirmationa and then depending on yes or no allow/disallow save.How can i do so..
On using confirm JS function it passes the statement and runs the Save procedure anyway.
my button's event
protected void btnSubmit_Click(object sender, EventArgs e)
{
string ListExam = string.Empty;
DataTable dt = BussObjGoalCert.CheckPlannedStatus(custObjGoalCert);
if (dt.Rows.Count != 0)
{
for (int i = 0; i < (dt.Rows.Count); i++)
{
ListExam = ListExam + (dt.Rows[i]["MultipleExamPlanned"]) + ";";
}
lblExamMultiple.Text = ListExam;
string myScript2 = "confirm('Unselected exam planned under other certification will also be unplanned.Do you wish to continue?');";
ClientScript.RegisterStartupScript(this.GetType(), "myScript", "confirm('Unselected exam planned under other certification will also be unplanned.Do you wish to continue?');", true);
}
Result = BussObjGoalCert.InsertGoalCertification(custObjGoalCert);
}
SO what I am doing is checking some data from backend and then trying to conditionally call the confirm function.
It IS CALLED but then Insert statement is also run irresepective of what the person chooses.
How can the database check be done within JS function.I need to do it in code behind. and yet allow/disallow complete save.How is this to be accomplished. I am not using OnCLientCLick as suggested in the answers.
Try this
If you have asp button
<asp:Button runat="server" ID="btn"
OnClientClick="return confirm('Are you surely want to submit (server button) ?');"
Text="Server button" />
If you have submit HTML button
<input type="submit"
onclick="return confirm('Are you surely want to submit (client button) ?');"
value="Client button" />
UPDATE
If you want to do this
Execute some server side code
Ask user for some confirmation
On user's confirmation execute some more server side code
Then should do following
Create a web service.
Use Jquery or Javascript to execute your server side code through that web service.
Display confirm box on complete(success) event of your web service request.
If user click's on YES perform a server side potback or perform one more web service request to execute the code to be executed on user's confirmation.
I think you are trying onclick event on submit button.
try onsubmit="return confirm('Are You sure to submit')" within form element
There is one solution for your problem.please follow these steps :
1.)On button's OnClientclick event call pagemethod and pass value in it which you want to check in Database.
2.)pagemethod is used to call server side static methods on client side and return result.
3.)Then return bool value from that in true if data exist and false if new.
4.)When flag is true then show confirmation box if confirmation is true then call server method again and update info and then return true to OnClientClick event.
OR
if confirmation is false then return false to OnClientClick event.
You can check my artical HERE.Hope this helps you.If you need more detail then please let me know.
try this
<asp:Button ID="btnsave" runat="server" Text="Save" OnClientClick="javascript:return Checkdelete();"/>
function Checkdelete() {
return confirm("Are you sure you want to Save the records");
}

onbeforeunload and asp:Update Panel in Safari and FireFox

I am working on a asp.net (framework 4) that has a requirement for the user to be notified if they are trying to leave the page without saving changes. Well I found a solution by calling the onbeforeunload function via JavaScript. Works great in IE but not in Firefox, Safari or Chrome.
Now here is where the problem comes in. I’m using AJAX postbacks and if the user is prompted to save the changes before leaving the page, any controls inside of the update panel no longer will postback to the server. For example, if a press the save button that is inside of the update panel, nothing happens.
Here are some code snippets
javascript:
window.onbeforeunload = function (e) {
if (doBeforeUnload() == true) {
var ev = e || window.event;
// For IE and Firefox prior to version 4
if (ev) {
ev.returnValue = "You have modified the data entry fields since the last time it was saved. If you leave this page, " +
"any changes will be lost. To save these changes, click Cancel to return to the page, and then Save the data.";
}
// For Safari
return "You have modified the data entry fields since the last time it was saved. If you leave this page, " +
"any changes will be lost. To save these changes, click Cancel to return to the page, and then Save the data.";
}
}
ASP.NET:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<%--no controls inside of this panel will postback to server if user clicks the “Stay on Page” button--%>
</ContentTemplate>
</asp:UpdatePanel>
Seems to be plenty of posts on the net but no solutions. Any ides besides not using async postbacks?
I came across this question when I was searching for the similar issue. I was able to solve this by doing the following:
var doOnBeforeUnloadCheck = true; // global to set in link button
window.onbeforeunload = function (e) {
if (doOnBeforeUnloadCheck && doBeforeUnload()) {
// do stuff
}
// Make sure to always re-enable check to ensure the event will still trigger
// where not specified to disable event.
doOnBeforeUnloadCheck = true;
}
In a LinkButton you just make sure to set the global to false before running any other javascript or doing the postback:
<asp:LinkButton ID="yourButton" runat="server"
OnClientClick="doOnBeforeUnloadCheck = false;" OnClick="yourButton_Click" />
I came across this solution with help from the following link:
http://www.jimandkatrin.com/CodeBlog/post/LinkButton-UpdatePanel-onbeforeunload.aspx
I found this question before I found my answer so if anyone else has the same issue this might save them some time. Hope that helps.

Leave Unsaved form: button submit event will reset the "Changed_Form" status

Please See the following code example.
HTML:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server" />
<!-- upload button and Save button -->
<asp:Button ID="Upload" runat="server" Text="Upload" />
<asp:Button ID="Save" runat="server" Text="Save" />
Cancel
JavaScript:
//form is not changed by default
var form_Change = 0;
window.onbeforeunload = function(e) {
if (form_Change==1){
// if the form is changed, show a confirm box
return 'Are you sure you want to navigate away from this page?';
}
}
$('input[type=text]').live('keyup',function(){
form_Change =1;
});
Normally,
A user typed in the textbox without saving it. Then he is trying to redirect to other page or reload the page, the bowser brings him a confirm box.
But,
I firstly type into the textbox, and then click the "Upload Button" which is used to upload files but doesn't save (doesn't affect the change of) the form (and keep the unsaved text in the textbox as it is after postback). The bowser brings me the unwanted confirm box.
I try to fix it and add something like,
var button_inside_form =0;
$('Upload').live('click',function(){
button_inside_form =1;
});
//and update form change logic in onbeforeunload
But, after the page post back. It reload JavaScripts, form_Change is reset to 0. so the system doesn't know whether the form is changed.
So how do I check the form is changed after I click "Upload", and don't bring back confirm box when I click "Upload".
Answer myself.
I use a cookies. that is turn var form_change as a cookies in JavaScript.
and then in server code, Not IsPostBack I add this to reset the cookies.
ClientScript.RegisterClientScriptBlock(Me.GetType, "IsPostBack", "var isPostBack = true;", True)
to check
if (typeof isPostBack != 'undefined') {
resetFormChange();}
use this to prevent the confirm box on submit buttons
$('form').submit(function() {
window.onbeforeunload = null;
});
More thinking.
The cookies is required, if the form submit will remain it in the same page.
form.submit will works fine, but need to make sure "UseSubmitBehaviors" need to be set on "Cancel" button. And or if cause the page stay, better to put them in a updatepanel.

Categories